user751254
user751254

Reputation: 11

DataGridView - ComboBox @ runtime

I have a DataGridView where I set the DataSource to a collection of objects when the tab the DataGridView resides is selected.

After the datasource is set I'd like to change the "County" column to a DataGridViewComboBoxColumn with the state's counties as the items. Nothing I've seen works yet - it always gives an exception.

Is there a way to change the column type without deleting it?

Is there a way to have a combobox or other control appear when I click on a cell in that row without having to modify the column type?

======================== My Failing Code ========================

//ii is a for loop variable on the dataGridViewFields.Columns.Count

string colName = dataGridViewFields.Columns[ii].Name;
if (colName.Equals("County"))
{
    string dpName = dataGridViewFields.Columns[ii].DataPropertyName;
    DataGridViewComboBoxColumn column = new DataGridViewComboBoxColumn();
    //get current column characteristics.
    column.ValueType     = dataGridViewFields.Columns[ii].ValueType; ;
    column.Name          = dataGridViewFields.Columns[ii].Name;
    column.HeaderText    = dataGridViewFields.Columns[ii].HeaderText;
    column.Width         = dataGridViewFields.Columns[ii].Width;
    //remove column from grid
    dataGridViewFields.Columns.RemoveAt(ii);
    //set column combobox characteristics
    column.DropDownWidth = 160;
    column.MaxDropDownItems = 10;

    column.Items.AddRange(new string[] {"Dane", "Dodge", "Door"});
    column.FlatStyle = FlatStyle.Flat;

    DataGridViewCell cell = new DataGridViewComboBoxCell();
    cell.Style.BackColor = Color.Wheat;
    cell.ValueType = typeof(string);
    cell.Value = "Door";
    column.CellTemplate = cell;
    //add to the grid.
    dataGridViewFields.Columns.Insert(ii, column);
    dataGridViewFields.Columns[ii].DataPropertyName = dpName;
    //dataGridViewFields.EditMode = DataGridViewEditMode.EditProgrammatically;
}

Upvotes: 1

Views: 2366

Answers (1)

V4Vendetta
V4Vendetta

Reputation: 38230

I think you would be interested in the DisplayStyle of the ComboBox Column

Set DisplayStyle to Nothing. This will make the ComboBox appear only when you try to Edit the cell

Upvotes: 1

Related Questions