简体   繁体   中英

NullReference exception occurs even when the object is not null

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

When text in the ComboBox is changed, the search result is displayed underneath the datagrid. When any row from the datagrid is selected its values are displayed in textboxes for editing.

When I write something in the combobox, the related 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 dataGrid refreshing logic was behind a button click.

The code for "SelectionChange" Event of the dataGrid is:

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 of ComboBox is:

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

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

  • categoryMember.CategoryName (the CategoryName property itself) returns null , as TextBox.Text and similar properties raise the exception if you set the value to null .
  • CategoryName (the control) is null

Also, I see you had a null check (for debugging?), but it is commented out. If CategoryDataGrid.SelectedItem is not assignable to CategoryTbl , you will receive null in categoryMember itself.

in addition to @Reed answer would say, that considering that you say that on Button click it works, I immagine Button was on the cell. In this case returned type is a different then may happen in CategoryDataGrid.SelectedItem . Most probabbly CategoryDataGrid.SelectedItem is a container of a some type and not directly of a type CategoryTbl

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM