3

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

Daniel
  • 1,391
  • 2
  • 19
  • 40

1 Answers1

1

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;
David Hall
  • 32,624
  • 10
  • 90
  • 127
  • This has two problems: 1. If DataGridView is data bound, then you can only assign a type to ValueMember that can be inserted into a DataTable and finally into SQL (how do you insert an 'Employee' object into an int column?), 2. I wanted to do this with DataRow class and not creating a custom class. – Daniel Oct 17 '11 at 10:19
  • @Daniel - you can't do what you want as far as I know. I'd advise using custom objects rather than datatables but if you must have a datatable then the best you will get is using the value member to lookup to datatable row you want. – David Hall Oct 17 '11 at 10:33
  • Thanks for the response. But how do I add a value into the datatable of the DataGridView in case I use a custom object? I cannot add an object to a DataTable. BTW I ended up doing a lookup in the DataTable by using the ValueMember as PK... just as you suggested and it works. But it would be more elegant to get the object itself. – Daniel Oct 17 '11 at 12:37
  • @Daniel with a custom object you create a list of that object which is your datasource source. Then you just add items to that list. I've always found this approach much more flexible than using DataTables but that is probably just me :) – David Hall Oct 17 '11 at 12:44