0

VS 2013: Winforms Combobox column of datagridview has a list of values, i.e. Tag, Reset, Cancel, etc... Datagridview is bound to datatable which is populated from SQL table. When combobox column encounters a value not in the list it errs out.

1) How can I get the value that is destined to populate the combobox column before it happens? If this is possible I can then add the value to the list as suggested in answer below.

Thom Ash
  • 221
  • 4
  • 20

2 Answers2

0

You should use null for the value in place of an empty string. The control already works with that.

It is not usually a good idea to try and use values not part of your combo cell. But if you insist on doing so you can check if there value is already there. If not add it then set the value.

var comboColumn = ((DataGridViewComboBoxColumn)grid.Columns["combo_column"]);
if (!comboColumn.Items.Contains(value)) 
     comboColumn.Items.Add(value);
Jeffrey Wieder
  • 2,336
  • 1
  • 14
  • 12
  • The problem is other applications set values in those columns and I can't control that. I know NULL works my application uses them but my question was how to make empty string an item in the combobox column list and/or how to ignore values not in the list. I'll try that with empty string but it would be better if I could just ignore values not in list. – Thom Ash May 27 '15 at 20:33
  • I got stuck trying to implement your answer. In order to set the variable value I have to get it from the datatable just before it populates the comboboxcolumn. I haven't been able to figure out the datatable row & column being worked on. I tried using the dgv e.RowIndex & e.ColumnIndex but they must not be the same as I get an exception. I'll update my question to include how to get the value before the combobox column is populated. – Thom Ash May 28 '15 at 02:47
0

Set up data error event on datagridview and then capture values in the event and set them in the comboboxcolumn item list as suggested in previous answer. The items will display in datagridview but will not be permanently stored in comboboxcolumn item list.

    private void dgvVX130DataErrors(object sender, DataGridViewDataErrorEventArgs e)
    {
        DataGridViewComboBoxColumn comboColumn;
        switch (e.ColumnIndex)
        {
            case 4:
                comboColumn = ((DataGridViewComboBoxColumn)dgvVX130.Columns["DataDomain"]);
                if (!comboColumn.Items.Contains(dgvVX130.Rows[e.RowIndex].Cells[e.ColumnIndex].Value))
                {
                   comboColumn.Items.Add(dgvVX130.Rows[e.RowIndex].Cells[e.ColumnIndex].Value);
                }
                break;
Thom Ash
  • 221
  • 4
  • 20