Search code examples
c#winformsdatagridviewdatagridviewcomboboxcell

c# Get DatagridviewComboBoxCell's Selected Value


I'm building a Winforms application which has a DataGridView. The DataGridView is not bound to a datasource. I have a comboboxColumn on my grid which I'm populating using a datatable.

When I try to retrieve the selectedValue of the comboBoxCell, it is giving the first matched value instead of the exact selected value.

Convert.ToString((datagridview1.Rows[i].Cells["columnName"] as DataGridViewComboBoxCell).Value)

For Example, The combobox datatable is

DisplayMember ValueMember
Orange        1111
Apple         2222
Banana        3333
Apple         4444
Guava         5555

Now, if I select the Apple with ID 4444, the above code gets the Apple with 2222.

I tried to perform the steps given in below link, but that is giving the index instead of the value.

https://stackoverflow.com/a/30157754/3619679


Solution

  • I was able to resolve the issue with help from the below link

    https://stackoverflow.com/a/30157754/3619679

    SelectedItem stores the correct value of the selected comboBox Item.

    private void datagridview1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
            {
                if (cmbCombo != null)
                {
                    DataRowView oDataRowView = cmbCombo.SelectedItem as DataRowView;
                    string sValue = string.Empty;
    
                    if (oDataRowView != null)
                    {
                        sValue = oDataRowView.Row["ValueMemberID"] as string;
                    }
                    datagridview1[e.ColumnIndex, e.RowIndex].Tag = sValue;
                }
    
            }