1

I'm creating a DataGridView with a column DataGridViewComboBoxColumn. Initially the combo box Items is filled with values using Items.Add("sometext").

Further values are added to the DataGridViewComboBoxEditingControl returned in the event EditingControlShowing of DataGridView.

Hereafter I can correctly select values added initially, but if I try selecting one added later an exception with message "DataGridViewComboBoxCell value is not valid." is thrown.

Any ideas why?

Mustafa Temiz
  • 326
  • 1
  • 4
  • 19

2 Answers2

3

You need to handle the ComboBoxValidating event and then add it there. Here's some code:

    private void HandleEditShowing(
        object sender, DataGridViewEditingControlShowingEventArgs e)
    {
        var cbo = e.Control as ComboBox;
        if (cbo == null)
        {
            return;
        }

        cbo.DropDownStyle = ComboBoxStyle.DropDown;
        cbo.Validating -= HandleComboBoxValidating;
        cbo.Validating += HandleComboBoxValidating;
    }

    private void HandleComboBoxValidating(object sender, CancelEventArgs e)
    {
        var combo = sender as DataGridViewComboBoxEditingControl;
        if (combo == null)
        {
            return;
        }
        //check if item is already in drop down, if not, add it to all
        if (!combo.Items.Contains(combo.Text))
        {
            var comboColumn = this.dataGridView1.Columns[
                this.dataGridView1.CurrentCell.ColumnIndex] as
                    DataGridViewComboBoxColumn;
            combo.Items.Add(combo.Text);
            comboColumn.Items.Add(combo.Text);
            this.dataGridView1.CurrentCell.Value = combo.Text;
        }
    }

So when you handle the EditingControlShowing event, hook into the combobox's Validating event. Then, that event will fire once the user enters some text into the DataGridView combo box and tabs out of it. At that point, you need to add it to the combo box itself, as well as to the actual DataGridViewColumn so that all other rows in the DataGridView have that value.

Ryan Lundy
  • 204,559
  • 37
  • 180
  • 211
BFree
  • 102,548
  • 21
  • 159
  • 201
0

Try this,

DataGridViewComboBoxColumn Column_ModemList = (DataGridViewComboBoxColumn)this.DGV_Groups.Columns["DGV_Groups_ModemList"];
Column_ModemList.Items.Add(l_modem_str);

Note: Set AllowUserToAddRows property to false.

skink
  • 5,133
  • 6
  • 37
  • 58
Nitin Gupta
  • 202
  • 3
  • 9