In the code below, the datagridview1_SelectionChanged event which fires after the selection has been changed through the code in datagridview1_RowsAdded event handler, the CurrentRow property is null. but I have just set it in datagridview1_RowsAdded handler and it is not null in there.
However, if I comment the two lines in datagridview1_RowsAdded handler and select the row through mouse click on any row, the program works fine. Can anyone tell me why this is happening?
Here’s my code:
private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
dataGridView1.CurrentCell = dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[1];
dataGridView1.CurrentCell.Selected = true;
}
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
if (dataGridView1.CurrentRow != null)
{
if (dataGridView1.CurrentRow.Index != -1)
{
dataGridView2.Enabled = true;
dataGridView3.Enabled = true;
dataGridView4.Enabled = true;
}
else
{
dataGridView2.Enabled = false;
dataGridView3.Enabled = false;
dataGridView4.Enabled = false;
}
}
else
{
dataGridView2.Enabled = false;
dataGridView3.Enabled = false;
dataGridView4.Enabled = false;
}
}
In your
RowsAddedmethod, you have selected the current cell but not the current row. You can select the current row with this: