DataGridViewComboBoxColumn中的单元格具有ComboBoxStyle DropDownList。 这意味着用户只能从下拉列表中选择值。 底层控件是ComboBox,因此它可以具有样式DropDown。 我如何更改DataGridViewComboBoxColumn中基础组合框的样式? 或者更一般地说,我能否在DataGridView中拥有一个带有下拉列表的列,让用户输入?
DataGridViewComboBoxColumn中的单元格具有ComboBoxStyle DropDownList。 这意味着用户只能从下拉列表中选择值。 底层控件是ComboBox,因此它可以具有样式DropDown。 我如何更改DataGridViewComboBoxColumn中基础组合框的样式? 或者更一般地说,我能否在DataGridView中拥有一个带有下拉列表的列,让用户输入?
void dataGridView1_EditingControlShowing(object sender,
DataGridViewEditingControlShowingEventArgs e)
{
if (e.Control.GetType() == typeof(DataGridViewComboBoxEditingControl))
{
DataGridViewComboBoxEditingControl cbo =
e.Control as DataGridViewComboBoxEditingControl;
cbo.DropDownStyle = ComboBoxStyle.DropDown;
}
}
以下解决方案对我有效:
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 (!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;
}