这是我第一次使用DataGridView,它有点压倒性(这么多选项!)。
我想显示一个属性列表,每行一个。每行都是名称/值对。属性的名称是固定的,但用户可以自由输入任何值。
现在,由于每个媒体资源都有一个已使用值列表,我希望用户可以在下拉列表中使用这些资源。但是,我也希望用户能够键入新值。理想情况下,该值应在用户输入时自动完成。
我尝试使用DataGridViewComboBoxColumn样式的列,并且由于标准组合框支持类型或编辑方式,我认为这样可行。但是,似乎仅允许从列表中进行选择(此外,按一个键将自动从列表中选择第一个匹配的条目)。似乎没有办法输入新值。
我应该设置844个属性中的哪一个? : - )
答案 0 :(得分:1)
您必须更改组合框DropDownStyle以允许用户在组合框处于编辑模式时输入文本,但标准DataGridView在设计时不允许这种行为,因此您必须提取一些技巧,处理CellValidating, EditingControlShowing和CellValidated事件。
这是代码(来自MSDN论坛,它适用于我)。
private Object newCellValue;
private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
if (dataGridView1.CurrentCell.IsInEditMode)
{
if (dataGridView1.CurrentCell.GetType() ==
typeof(DataGridViewComboBoxCell))
{
DataGridViewComboBoxCell cell =
(DataGridViewComboBoxCell)dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
if (!cell.Items.Contains(e.FormattedValue))
{
cell.Items.Add(e.FormattedValue);
cell.Value = e.FormattedValue;
//keep the new value in the member variable newCellValue
newCellValue = e.FormattedValue;
}
}
}
}
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (e.Control.GetType() ==
typeof(DataGridViewComboBoxEditingControl))
{
((ComboBox)e.Control).DropDownStyle = ComboBoxStyle.DropDown;
}
}
private void dataGridView1_CellValidated(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView1.CurrentCell.GetType() ==
typeof(DataGridViewComboBoxCell))
{
DataGridViewCell cell =
dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
cell.Value = newCellValue;
}
}