DataGridView selectionChanged event firing multiple times

Sanjeev4evr picture Sanjeev4evr · Apr 10, 2014 · Viewed 12.1k times · Source

In my application I am using DataGridView to display the list. When user select a record in the datagridview, it should display details in the other panel. For selection I was asked to use DataGridView1_SelectionChanged event.

The DataGridView should contain only one column, but the details display may have more information of the selected record( We can get the all the details form the database by querying with the selected Primary key value).

Please tell Is it possible to get datakey(Primary key) of the selected DataGridView record. Does DataGridView will bind based on Primary key ?

Edit

I have implemented DataGridView1.Columns["ID"].Visible = false. It worked well. For selection I added DataGridView1_SelectionChanged event.

But DataGridView1_SelectionChanged event is firing multiple times.

Answer

Mustafa Yasser picture Mustafa Yasser · Sep 5, 2015

You can use DataGrid.focused property in selectionchanged event before executing the code like this :

private void dg_SelectionChanged(object sender, EventArgs e)
    {
        if (dg.Focused)
        {
            // your code
        }
    }