koviroli
koviroli

Reputation: 1453

Disable item in Combobox in DataGridViewComboBoxCell

I'd like to disable item in ComboBox that is in a DataGridview cell.

I already know how to disable(or seems disabled) items in a ComboBox, using the DrawItem event and SelectedIndexChanged event but there is no similar event in DataGridViewComboBoxCell or DataGridViewComboBoxColumn.

So my question is, how to disable any item in ComboBox that is in a DataGridView?

In ComboBox I can modify items display that need to be disabled like this: enter image description here

But can't do the same functionality in DataGridView:

enter image description here

Upvotes: 1

Views: 805

Answers (1)

JayV
JayV

Reputation: 3271

I think the simplest option for you would be to handle the EditControlShowing event, and then handle the ComboBoxes SelectedIndexChanged event and do what you already know how to do.

When you setup the DataGridview in code, you can do this:

dataGridView1.EditingControlShowing += dataGridView1_EditingControlShowing;

And then implement the handler like:

void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
    ComboBox combo = e.Control as ComboBox;

    if (combo != null)
    {
        // Both of these lines are essential, otherwise you will be handling the same event twice in some conditions
        combo.SelectedIndexChanged -= combo_SelectedIndexChanged;
        combo.SelectedIndexChanged += combo_SelectedIndexChanged;
    }
}

Finally, the SelectedIndexChanged event is handled exactly the way you want to:

void combo_SelectedIndexChanged(object sender, EventArgs e)
{
    ComboBox thisCombo = sender as ComboBox;
    if (thisCombo != null)
    {
        Debug.Print(thisCombo.Text);
    }
}

Upvotes: 2

Related Questions