1
votes

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;
3
I thinks your problem is that 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
I want to show grid in specific situation. At the beginning grid must be hidden.revelvice

3 Answers

3
votes

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

1
votes

Set DataGridView's TabStop to false

0
votes

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");
}