如何在DataGridViewComboBoxColumn中更改单元格的ComboBox样式

8

DataGridViewComboBoxColumn中的单元格具有ComboBoxStyle DropDownList。 这意味着用户只能从下拉列表中选择值。 底层控件是ComboBox,因此它可以具有样式DropDown。 我如何更改DataGridViewComboBoxColumn中基础组合框的样式? 或者更一般地说,我能否在DataGridView中拥有一个带有下拉列表的列,让用户输入?

3个回答

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

组合框和数据绑定的数据网格视图问题


(说明:该链接是一个关于组合框和数据绑定的数据网格视图问题的论坛帖子)

这只是解决方案的想法。完整的解决方案需要验证例程,否则DataGridView将抛出异常。有用的解决方案通常还需要下拉列表中特定于单元格的列表。 - chgman

2

以下解决方案对我有效:

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 条件总是为真...有没有解决方法...

给定条件:

if (!Column1.Items.Contains(e.FormattedValue.ToString())) { Column1.Items.Add(e.FormattedValue); dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = e.FormattedValue; }
- Asad Malik

1
if (!Column1.Items.Contains(e.FormattedValue.ToString())) { 
    Column1.Items.Add(e.FormattedValue);     
    dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = e.FormattedValue; 
}  

可能总是返回true,因为Column1.Items.Contains()正在搜索String值。如果e.FormattedValue不是String,则比较将失败。

尝试一下

if (!Column1.Items.Contains(e.FormattedValue.ToString())) { 
    Column1.Items.Add(e.FormattedValue.ToString());     
    dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = e.FormattedValue.ToString(); 
}

或者

if (!Column1.Items.Contains(e.FormattedValue)) { 
    Column1.Items.Add(e.FormattedValue); 
    dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = e.FormattedValue; 
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接