Handling double-click events in a grid

Here's a handy little tip for those of you using DataGrids or something similar, for instance, the Telerik RadGrid control. If you want to allow the user to double-click on a row to do something (edit the row, for example), implement the CellDoubleClick event handler for the grid and put your code in there.

If you do this, then double-clicks in the column header will also fire the event; this can happen if a user clicks the header too quickly while trying to sort. To prevent this, add code to check e.RowIndex. If the user double-clicked on a header, e.RowIndex will = -1.

Here's some example code for a RadGrid:

private void radGrid1_CellDoubleClick(object sender, GridViewCellEventArgs e)
{
     if (e.RowIndex != -1) // Edit on double click, except when on the header.
      {
           DoSomethingSpecial();
      }
}
and for a DataGrid:

private void
dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
    if (e.RowIndex != -1) // Edit on double click, except when on the header.
 {
DoSomethingSpecial();
}
}


comments powered by Disqus