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