Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve datarow behind datagridviewcombobox while databound

I have a databound DataGridView. One of its columns is DataGridViewComboBox. The DataGridViewComboBox is also databound. Everything is working just fine until I wish to retrieve the DataRow behind the DataGridViewComboBox selected item (not the DataRow of the DataGridView but the datarow that fills the combobox's DisplayMember and ValueMember!).

How can I accomplish this? I need this because I need to display a whole bunch of data beside DisplayMember and ValueMember and this data is present inside the datarow of the DataTable to which the DataGridViewComboBox is bound.

Thanks for your kind help in advance.

Daniel

like image 951
Daniel Avatar asked Feb 25 '26 06:02

Daniel


1 Answers

This is detailed in this MSDN article.

What you need to do is set the ValueMember of the ComboBox column to a property that returns a reference to the business object itself.

That is, say you have an Employee object, and a list of them are the DataSource for the ComboBox column. Employee would perhaps look like this:

public Employee
{
    int Age { get; set; }
    string Name { get; set;}
    Employee Self
    {
        get { return this; }
    }
} 

Then you create your ComboBox columns like so:

DataGridViewComboBoxColumn col = new DataGridViewComboBoxColumn();
col.Name = "Combo";
col.ValueMember = "Self";
col.DisplayMember = "Name";
datagridview1.Columns.Add(col);

Then when you retrieve the Value property of a ComboBox cell you get an Employee object back:

Employee e = datagridview1.Rows[0].Cells["Combo"].Value as Employee;
like image 76
David Hall Avatar answered Feb 27 '26 20:02

David Hall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!