I have little problem with DataGridView.
1. Drop DataGridView control on form and set property Visible to False
2. Add few rows and change visible to True like code above.
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.Rows.Add(new object[] { "1", "a" });
dataGridView1.Rows.Add(new object[] { "2", "b" });
dataGridView1.Rows.Add(new object[] { "3", "c" });
dataGridView1.Rows.Add(new object[] { "4", "d" });
dataGridView1.Visible = true;
//^ this trigger selection
}
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
Console.WriteLine("selected");
}
After setting Visible to True, first cell is automatically selected and trigger SelectionChanged event.
How to prevent that?
EDIT. SOLUTION:
- Detach event handler:
- Set visible
- Clear selection
- Add handler
dataGridView1.SelectionChanged -= dataGridView1_SelectionChanged;
dataGridView1.Visible = true;
dataGridView1.ClearSelection();
dataGridView1.SelectionChanged += dataGridView1_SelectionChanged;
dataGridView1_SelectionChanged
is being fired because of this line of code:dataGridView1.Visible = true;
. Setting the grid's visibility will trigger the event. Why do you want to set the grid to false in the beginning? – KaeL