Cells in DataGridViewComboBoxColumn have ComboBoxStyle DropDownList. It means the user can only select values from the dropdown. The underlying control is ComboBox, so it can have style DropDown. How do I change the style of the underlying combo box in DataGridViewComboBoxColumn. Or, more general, can I have a column in DataGridView with dropdown where user can type?
A DataGridViewComboBoxColumn don't have a DropDownStyle property. You can't change the style of in DataGridView, it's limited to DropDownList style by default. In an EditingControlShowing event of DataGridView, you can change style to DropDown.
When a cell is in edit mode, it always looks like a ComboBox control. If the DisplayStyleForCurrentCellOnly property value is false, the DisplayStyle property affects all cells in the column; otherwise, the DisplayStyle property affects only the current cell.
By default a DataGridViewComboBoxCell does not support typing into the cell. There are reasons though that typing into the combo box works well for your application. To enable this, two things have to be done. First the DropDownStyle property of the ComboBox editing control needs to be set to DropDown to enable typing in the combo box.
First the DropDownStyle property of the ComboBox editing control needs to be set to DropDown to enable typing in the combo box. The second thing that needs to be done is to ensure that the value that the user typed into the cell is added to the combo box items collection.
void dataGridView1_EditingControlShowing(object sender,
DataGridViewEditingControlShowingEventArgs e)
{
if (e.Control.GetType() == typeof(DataGridViewComboBoxEditingControl))
{
DataGridViewComboBoxEditingControl cbo =
e.Control as DataGridViewComboBoxEditingControl;
cbo.DropDownStyle = ComboBoxStyle.DropDown;
}
}
Problem with combobox and databound datagridview
Following solution works for me
private void dataGridView1_CellValidating(object sender,
DataGridViewCellValidatingEventArgs e)
{
if (e.ColumnIndex == Column1.Index)
{
// Add the value to column's Items to pass validation
if (!Column1.Items.Contains(e.FormattedValue.ToString()))
{
Column1.Items.Add(e.FormattedValue);
dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value =
e.FormattedValue;
}
}
}
private void dataGridView1_EditingControlShowing(object sender,
DataGridViewEditingControlShowingEventArgs e)
{
if (dataGridView1.CurrentCell.ColumnIndex == Column1.Index)
{
ComboBox cb = (ComboBox)e.Control;
if (cb != null)
{
cb.Items.Clear();
// Customize content of the dropdown list
cb.Items.AddRange(appropriateCollectionOfStrings);
cb.DropDownStyle = ComboBoxStyle.DropDown;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With