开发者

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.开发者_JAVA技巧EditMode = DataGridViewEditMode.EditProgrammatically;
}


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜