Selected Values Of Combobox Inside DatagridView

In the previous blog, we learned how to place drop down inside DataGridView cell on cell click, and binding of dropdown with datatable.

Now, we will see how to get Selected Values of Combobox from DataGridView.

Step 1: Register handler of “SelectedIndexChange” with dropdown of DataGridView.

  1. ComboBox editGridCellComboBox = new ComboBox();  
  2. /// <summary>  
  3. /// Control for editing a cell is showing.  
  4. /// </summary>  
  5. /// <param name="sender"></param>  
  6. /// <param name="e"></param>  
  7. private void dgv_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)  
  8. {  
  9.     editGridCellComboBox = (ComboBox) e.Control;  
  10.     if ((editGridCellComboBox != null)) {  
  11.         editGridCellComboBox.SelectedIndexChanged += editGridCellComboBox_SelectedIndexChanged;  
  12.     }  
  13. }  
Step 2: Create event handler method “editGridCellComboBox_SelectedIndexChanged”.
  1. private void editGridCellComboBox_SelectedIndexChanged(System.Object sender, System.EventArgs e)   
  2. {  
  3.     if (editGridCellComboBox.SelectedItem != null) {  
  4.         editGridCellComboBox.SelectedIndexChanged -= editGridCellComboBox_SelectedIndexChanged;  
  5.         if (dgv.Columns[dgv.CurrentCell.ColumnIndex].Name.Equals("Description")) {  
  6.             string Description = ((DataRowView) editGridCellComboBox.SelectedItem).Row["Description"].ToString();  
  7.             string Type = ((DataRowView) editGridCellComboBox.SelectedItem).Row["Type"].ToString();  
  8.         }  
  9.         if (dgv.Columns[dgv.CurrentCell.ColumnIndex].Name.Equals("PaidWith")) {  
  10.             string PaidWith = ((DataRowView) editGridCellComboBox.SelectedItem).Row["PaidWith"].ToString();  
  11.             string Code = ((DataRowView) editGridCellComboBox.SelectedItem).Row["Code"].ToString();  
  12.         }  
  13.         editGridCellComboBox.SelectedIndexChanged += editGridCellComboBox_SelectedIndexChanged;  
  14.     }  
  15. }  
Note: The following lines are used to bring DataGridView and its dropdown in edit mode, in a single cell click.
  1. dgv.BeginEdit(false);  
  2. editGridCellComboBox.DropDownHeight = 170;  
  3. editGridCellComboBox.DroppedDown = true;  
In the next blog, we will learn how to set hyperlink on email and weblink columns of DataGridView with the help of datagridviewcell style.

 

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now