Mustafa Temiz
Mustafa Temiz

Reputation: 326

Add items to DataGridViewComboBoxColumn in DataGridView during runtime

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?

Upvotes: 1

Views: 13445

Answers (2)

BFree
BFree

Reputation: 103740

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.

Upvotes: 3

Nitin Gupta
Nitin Gupta

Reputation: 202

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.

Upvotes: 0

Related Questions