A NullReference exception occurs even when the object is not null

I am new to wpf; I am using editable comboBox (for search purposes).

When changing text in a ComboBox, the search result is displayed below the datagrid. When any row from a data file is selected, its values ​​are displayed in text boxes for editing.

When I write something in combobox, the corresponding row is displayed in the data grid, but when I click to select a row, the application throws a nullreference exception .

My application worked correctly when the logic for updating the DataGrid data was behind the button.

Code for the "SelectionChange" DataGrid Event:

 private void CategoryRowSelected(object sender, System.Windows.Controls.SelectedCellsChangedEventArgs e) { ClearForm(); if(CategoryDataGrid.SelectedItem!=null) { categoryMember = CategoryDataGrid.SelectedItem as CategoryTbl; // value assigned to the object // if (categoryMember != null) CategoryName.Text = categoryMember.CategoryName; //Exception thrown on this statement CategoryDescription.Text = categoryMember.CategoryDescription; } } 

and code for the textChange event for ComboBox:

 private void RefreshDataGrid(object sender, System.Windows.Controls.TextChangedEventArgs e) { CategoryDataGrid.SelectedIndex = -1; //CategoryDataGrid.ItemsSource = RefreshQuery; CategoryDataGrid.ItemsSource= Admin.RefreshCategoryDataGrid(NameCombo.Text); } 
+4
source share
2 answers
  CategoryName.Text = categoryMember.CategoryName; //Exception thrown on this statement 

This can happen for several reasons - not just because categoryMember is null. This will also happen if:

  • categoryMember.CategoryName ( CategoryName property) returns null , because TextBox.Text and similar properties throw an exception if you set it to null .
  • CategoryName (control) null

Also, I see that you had a null check (for debugging?), But it is commented out. If CategoryDataGrid.SelectedItem not assigned to CategoryTbl , you will get zero in categoryMember itself.

+5
source

in addition to the answer, @Reed will say that, given that you say that click on Button , it works, I immagine Button was in a cell. In this case, the return type is different from the other, it can happen in CategoryDataGrid.SelectedItem . The most likely CategoryDataGrid.SelectedItem is a container of some type, and not directly of type CategoryTbl

Hope this helps.

+1
source

Source: https://habr.com/ru/post/1436216/


All Articles