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开发者_如何学Go 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;
Your solution will prevent the event from firing, but I think the first cell will still be selected when the grid is shown. A simple call to ClearSelection() on the DataGridView should fix that.
Regards, Drew
Set DataGridView's TabStop to false
Instead of wiring and rewiring every time you alter the visible property, can you just not return from the method, if the visibility is false. That is:
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
if (!dataGridView1.Visible) return;
Console.WriteLine("selected");
}
精彩评论