views:

198

answers:

1

I don't know if my mind is not working today or if this is actually harder than I think it should be.

I've got a DataGridView with a DataGridViewComboBoxColumn bound to a generic IList of CustomObjects. Here's a rough code sample of how I setup the column.

DataGridViewComboBoxColumn location = new DataGridViewComboBoxColumn() 
{
    Name = "Location",
    DataSource = new BindingSource(GetMyLocations(), null),
    DisplayMember = "Name",
    ValueMember = "ID"
};

Then when I want to return the value of a cell:

string id = (string)row.Cells["Location"].Value;

But I don't want a reference to the ID property, I want a reference to the actual Location object! I've tried not specifying a ValueMember but that appears to just use the DisplayMember.

I could iterate through all of the Location objects in the column DataSource and check for the matching ID property, however, it seems like the ComboBoxCell ought to be able to return that directly.

Also, I can't use a Dictionary in this case.

Any ideas as to the best way to accomplish that?

+1  A: 

You could use an IList of KeyValuePairs of "Name" and your custom object. The idea is you need ValueMember to point to a reference of your object. I remember having similar issues for a while with ComboBoxes.

Something like the following ought to do the trick (off the top of my head and untested):

IList<KeyValuePair<String,MyObject>> comboData = 
    new IList<KeyValuePair<String,MyObject>>();

foreach(var o in GetMyLocations())
    comboData.Add(new KeyValuePair<String,MyObject>(o.Name, o));

DataGridViewComboBoxColumn location = new DataGridViewComboBoxColumn()
{
    Name = "Location",
    DataSource = comboData,
    DisplayMember = "Key",
    ValueMember = "Value"
};

You might want to change GetMyLocations() to return the KeyValuePair list instead, so you're not populating two lists for no reason.

lc