Saturday, November 19, 2016

DataGridViewComboBoxColumn show Dropdown in single click instead of double click

Hi,
When adding DataGridViewComboBoxColumn control to a DataGridView control, the dropdown shows when you double click instead of single click. The common fix to this is to set the EditMode property to EditOnEnter. Given that you don't want to alter the default settings of the DataGrid control and you want to handle it through code,I found the solution in this website DATAGRIDVIEWCOMBOBOXCOLUMN REQUIRES MULTIPLE CLICKS TO SELECT AN ITEM from a comment made by a developer. However, there's a slight issue in the code provided since a column index returned might have a -1 index and this will cause an Unhandled Exception. The revision made is to add a condition that will check if the ColumnIndex of the DataGridView cell is greater than or equal to 0.
private void DataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
 DataGridView grid = (DataGridView)sender;
 if (e.ColumnIndex >= 0)
 {
  if (grid.Columns[e.ColumnIndex].Name == "Role" || grid.Columns[e.ColumnIndex].Name == "Employee")
  {
   grid.BeginEdit(true);
   ((ComboBox)grid.EditingControl).DroppedDown = true;
  } 
 }
}                
That's it. :-)

0 comments:

Post a Comment