views:

528

answers:

3

Hi, I have a DataGridViewComboBoxCell, whose DataSource is a List. When an item is selected from the list, I wish to store the index of the item, not the item itself, in order that I can switch DataSources and still display a relating list entry.

e.g. I have a list of months (January-December). I want to select "April" and store "3" in the cell (but still display "April" as the selected value). I then decide to display all the month values in Polish, change the DataSource, and the value of "4" now displays "kwiecień".

I've looked into DisplayMembers and ValueMembers and things like the GetFormattedValue and GetEditedFormattedValue functions, but I can't make head nor tail of it. Most of it seems to be designed for use with database data, and that's not what I'm using here.

Can someone with insight tell me the best calls to override in order to get the sort of behaviour I'm looking for?

A: 

Try using the editing control property of the DataGridView. That should give you access to the properties of the combo box.

Here is an quick example.

    private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
        // Cast the editing control as a ComboBox to get to the selected index property
        ComboBox cb = dataGridView1.EditingControl as ComboBox;
        if (cb != null)
        {
            int selectedIndex = cb.SelectedIndex;
        }
    }
WaterBoy
+1  A: 

You shouldn't need to override anything to make this work.

Create a class with 2 properties ID and MonthName and store instances of that class in your list. Then setting ValueMember = "ID" and DisplayMember = "MonthName" should work.

I can give an example. Are you using C# or VB.NET?

Dennis Palmer
A: 

I eventually ended up making my data object implement the iBindingList interface, as covered in another question I asked along with overriding the GetValue and SetValue methods of my DataGridViewCell.
Frankly, most of my difficulties over the past week or so came from the fact that I couldn't override the Value property of the DataGridViewCell. Discovering that I could override these methods instead of the property, and achieve the same result, was something of a godsend.

Frosty840