1

I'm getting really tire of this error. What object,what reference, what...Sigh... Anyway, what I'm doing here is filling a data grid with data from the database. I'm looking for my record... regardless of whether or not I actually select an item, when I press the search button again (maybe to refine the search params), I get the error about "object reference not set to an instance of an object". It keeps crapping out on the "Pnum" line in the code below:

private void DgPatSrch_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {

        var id = ((DataRowView)DgPatSrch.SelectedItem).Row["Pnum"].ToString();
        var name = ((DataRowView)DgPatSrch.SelectedItem).Row["Pname"].ToString();
        var dob = ((DataRowView)DgPatSrch.SelectedItem).Row["Dob"].ToString();
        TbPatIdReadOnly.Text = id;
        TbPatNameReadOnly.Text = name;
        TbDobReadOnly.Text = dob;

    }

So, how would I fill a data grid, not like what I filled it with, pass new params, and repopulate it? Everything seems to work EXCEPT the repopulate. It almost seems like I need to reinitialize the data grid or clear or refresh... but none of those have worked... Help please!!!

RazorSharp
  • 179
  • 1
  • 3
  • 15
  • My bad. What is the ItemsSource of the datagrid? Should have asked that first. I may need to edit my answer after rereading your post – Nkosi Apr 28 '16 at 03:58
  • Please debug the problem deeply enough that you can get farther than asking about the `NullReferenceException` itself. You should not even need to mention the exception; your debugging should take you to the root cause, and you should ask a question about _that_. Please also make sure you provide a good [mcve] that reliably reproduces the problem, so we can avoid people posting guesses as answers. Sometimes the guesses will be right, but too often they are not. – Peter Duniho Apr 28 '16 at 04:17

1 Answers1

3

That is because the SelectedItem will become null when you repopulate the grid.

You will want to first extract the selected item, cast it to the correct type as SelectedItem property returns an object and then use the cast object as needed. This is provided it is not null

private void DgPatSrch_SelectionChanged(object sender, SelectionChangedEventArgs e) {
    var selectedItem = DgPatSrch.SelectedItem as DataRowView;
    if(selectedItem != null) {
        var id = selectedItem.Row["Pnum"].ToString();
        var name = selectedItem.Row["Pname"].ToString();
        var dob = selectedItem.Row["Dob"].ToString();
        TbPatIdReadOnly.Text = id;
        TbPatNameReadOnly.Text = name;
        TbDobReadOnly.Text = dob;
    }
}
Nkosi
  • 235,767
  • 35
  • 427
  • 472