8

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?

4

3 回答 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;
    }
}

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

于 2008-10-14T19:21:25.110 回答
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;
        }
    }
}
于 2008-10-15T02:03:23.177 回答
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不是 aString那么比较将失败。

尝试

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; 
}
于 2011-07-28T23:47:47.820 回答