views:

62

answers:

1

Hi. I've got a DataGridView control which is bound to a database table. I want one of the columns in the gridview to be of combobox type. The combobox should contain a list of hardcoded strings, which is the same for all rows in the datagridview. One of the fields in my database table is an index for this list of hardcoded strings.

I've programatically added a new column to the gridview of type "DataGridViewComboBoxColumn", which successfully creates the column with comboboxes in it. However, that's then not bound to the index field in my DB table.

The index field in my DB table is actually automatically bound to a column via the DataAdapter::Fill method. I've set this column to hidden, so it's hidden to the user.

Obviously just before updating the dataadapter, I can programatically fixup the hidden column in my datatable with the SelectedIndex of my combobox. Just wondering if there's a better way of doing this?

[edit]
Actually rather than doing it just before updating the dataadapter, I'm probably best using the comboboxes cell change event to update the hidden column. Not sure if I'm answering my own question here, or if there's a better way of doing this. It does seem to work, but just feels a bit of a workaround. [/edit]

Thankyou for any help with this,
Dan.

+2  A: 

If you need the SelectedValue of the ComboBox to be an index rather than a string, fill the ComboBox with a list of custom objects rathen than a list of strings :

dgvComboColumn.DataSource = new []
{
    new { Index = 1, Text = "Foo" },
    new { Index = 2, Text = "Bar" },
    new { Index = 3, Text = "Baz" }
};
dgvComboColumn.DisplayMember = "Text";
dgvComboColumn.ValueMember = "Index";
dgvComboColumn.DataPropertyName = "(the DB column that stores the index)";
Thomas Levesque
Fantastic! I was already using a custom object and setting the DisplayMember and ValueMember properies - however, I didn't know about DataPropertyName! That's just solved in one line, what took me hours to hack around! ;-) I knew there must have been an easier way. Thankyou!
Dan