DataGridView - ComboBox @ runtime

时间:2011-05-13 11:35:47

标签: c# visual-studio-2010 datagridview

我有一个DataGridView,当选中DataGridView所在的选项卡时,我将DataSource设置为一个对象集合。

设置数据源后,我想将“县”列更改为DataGridViewComboBoxColumn,并将州的县作为项目。我所看到的一切都没有作用 - 它总是有例外。

有没有办法更改列类型而不删除它?

当我点击该行中的单元格而不必修改列类型时,是否有办法显示组合框或其他控件?

========================我的失败代码==================== ====

//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;
}

1 个答案:

答案 0 :(得分:1)

我想你会对ComboBox专栏的DisplayStyle感兴趣

将DisplayStyle设置为Nothing。当您尝试编辑单元格

时,这将使 ComboBox仅显示