0

I have a DataGrid in WinForms which I use to show data from an Access Database. I made a method to refresh the DataGrid each time I add or edit something to the Database but I have some controls which I update based on the selected row from the DataGrid and I get a null reference exception from them because of the refresh method.

Here is the refresh method:

        private void refresh_mydatagrid()
    {

        this.table1TableAdapter.Fill(this.raspunsDataSet.Table1);
        this.dataGridView1.PerformLayout();
        this.dataGridView1.EndEdit();
        this.dataGridView1.Refresh();
        this.dataGridView1.Parent.Refresh();

    }

And here is the method that updates the controls based on the current selected row:

  private void row_click(object sender, EventArgs e)
    {  //any of these will cause a null reference exception 
        labelT2ID.Text = dataGridView1.CurrentRow.Cells[0].Value.ToString(); 
        comboBoxT2.Text = dataGridView1.CurrentRow.Cells[1].Value.ToString();
        if (dataGridView1.CurrentRow.Cells[2].Value.ToString().Contains("Barbat"))
            radioButtonT2Barbat.Checked = true;
        else
            radioButtonT2Femeie.Checked = true;
        if (dataGridView1.CurrentRow.Cells[3].Value.ToString().Contains("Da"))
            radioButtonT2R1Da.Checked = true;
        else
            radioButtonT2R1Nu.Checked = true;
        if (dataGridView1.CurrentRow.Cells[4].Value.ToString().Contains("Da"))
            radioButtonT2R2Da.Checked = true;
        else
            radioButtonT2R2Nu.Checked = true;
        if (dataGridView1.CurrentRow.Cells[5].Value.ToString().Contains("Da"))
            radioButtonT2R3Da.Checked = true;
        else
            radioButtonT2R3Nu.Checked = true;
        if (dataGridView1.CurrentRow.Cells[6].Value.ToString().Contains("Da"))
            radioButtonT2R4Da.Checked = true;
        else
            radioButtonT2R4Nu.Checked = true;
    }

I also use the selected row to get the ID for which entry to edit in the database so I need it. How can I get around this?

SharpGobi
  • 144
  • 1
  • 13
  • Check if the CurrentRow is null and return if true. For a complete explanation of a NullReferenceException see the duplicate – Steve Jun 04 '17 at 17:55
  • Thanks @Steve, I actually tried that initially but it didn't work because I was checking CurrentRow.Cells for some reason. I feel dumb now. – FullStackOverflowDev Jun 04 '17 at 18:02

0 Answers0