tags:

views:

774

answers:

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?

+2  A: 

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;
        }
        if (!combo.Items.Contains(combo.Text)) //check if item is already in drop down, if not, add it to all
        {
            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.

BFree