views:

3837

answers:

3

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?

+2  A: 
void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
    if (e.Control.GetType() == typeof(DataGridViewComboBoxEditingControl))
    {
        DataGridViewComboBoxEditingControl cbo = e.Control as DataGridViewComboBoxEditingControl;
        cbo.DropDownStyle = ComboBoxStyle.DropDown;
    }
}

http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=13855&SiteID=1

Aleris
This is only idea of the solution. Complete solution requires validation routine, otherwise DataGridView will throw an exception. Useful solution also often requires cell specific list in dropdown.
chgman
A: 

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;
     }
    }
   }
chgman
the given if condition always turns out to be true in my databounded combobox...is there a work around...given condition:===================================================================if (!Column1.Items.Contains(e.FormattedValue.ToString())) { Column1.Items.Add(e.FormattedValue); dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = e.FormattedValue; }
Asad Malik
A: 

ok the second answer works...

but to work around data-bounded combobox column...?

Asad Malik