Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataGridViewComboBox - How to allow any value?

Tags:

c#

winforms

I'm having some trouble with VisualStudio 2010 C# Winforms.

I have created a DataGridView with an unbound column that is of type DataGridViewComboBoxColumn. The column works fine, except unlike a normal ComboBox, I can't seem to type in just any value. I am forced to pick a value from the list.

Is there a property I need to set or another type I can use that will allow me to enter any value in the cell in addition to providing a list to pick a value from?

Thanks!

like image 598
Tim Reddy Avatar asked Nov 19 '10 22:11

Tim Reddy


1 Answers

I don't think there is a property that will allow this, but I found an answer here that worked with a small modification.

Try adding the following 2 event handlers, here assuming a column named comboBoxColumn:

private void dataGridView1_EditingControlShowing(object sender, 
        DataGridViewEditingControlShowingEventArgs e)
{
    ComboBox c = e.Control as ComboBox;
    if (c != null) c.DropDownStyle = ComboBoxStyle.DropDown;
}

private void dataGridView1_CellValidating(object sender, 
        DataGridViewCellValidatingEventArgs e)
{
    if (e.ColumnIndex == comboBoxColumn.Index)
    {
        object eFV = e.FormattedValue;
        if (!comboBoxColumn.Items.Contains(eFV))
        {
            comboBoxColumn.Items.Add(eFV);
            dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = eFV;
        }
    }
}
like image 123
Jeff Ogata Avatar answered Oct 03 '22 14:10

Jeff Ogata