C# – Prevent selecting cell in DataGridView

cdatagridviewnetselectionwinforms

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;

Best Answer

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

Related Topic