我发现一个简单的,如果详细的答案。 (但我仍然想知道是否有办法用标准DataGridViewComboBoxColumn
类型来做到这一点。)
我遵循How to: Host Controls in Windows Forms DataGridView Cells中的方法。我的完整解决方案太长,无法在此处发布,但我可以总结所做的更改,以便使用ComboBox
而不是示例的DateTimePicker
控件。
分别DropDownComboBoxColumn
,DropDownComboBoxCell
和DropDownComboBoxEditingControl
重命名三类。
用string
替换DateTime
无处不在。
添加属性public ComboBoxStyle DropDownStyle { get; set; }
到DropDownComboBoxColumn
允许调用代码设置下拉样式。
从DropDownComboBoxCell
构造函数中删除代码。
从DropDownComboBoxEditingControl
构造函数中删除代码。
制造DropDownComboBoxEditingControl
派生自ComboBox
而不是DateTimePicker
。
更换OnValueChanged
与OnTextChanged
,以考虑ComboBox
与DateTimePicker
不同的命名。
使EditingControlFormattedValue
属性获取并设置继承的Text
属性(而不是Value
),并且不需要解析。
让ApplyCellStyleToEditingControl
设置ForeColor
和BackColor
代替CalendarForeColor
和CalendarMonthBackground
。
制作EditingControlWantsInputKey
也声称F4,因此它可以用来打开和关闭下拉菜单。
下面的代码添加到PrepareEditingControlForEdit
:
DropDownComboBoxColumn col = _dataGridView.Columns[_dataGridView.CurrentCell.ColumnIndex] as DropDownComboBoxColumn;
if (col == null)
{
throw new InvalidCastException("Must be in a DropDownComboBoxColumn");
}
DropDownStyle = col.DropDownStyle;
// (If you don't explicitly set the Text then the current value is
// always replaced with one from the drop-down list when edit begins.)
Text = _dataGridView.CurrentCell.Value as string;
SelectAll();
处理的DataGridView
的EditingControlShowing
事件是OhBeWise's回答一个相关的问题设置下拉项目,如果需要,自动 - 完成模式:
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
ComboBox box = e.Control as ComboBox;
if (box != null)
{
box.AutoCompleteSource = AutoCompleteSource.ListItems;
box.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
box.DataSource = _dropDownItems;
}
}
如果你想要所有行的相同的下拉项目,那么你可以总是s请将其设为DropDownComboBoxColumn
的财产,如DropDownStyle
,并将其设置为PrepareEditingControlForEdit
以避免必须处理EditingControlShowing
。
@Ian Goldby,如果有帮助,请将其标记为答案,以便其他人也可以从中受益,如果您有任何疑问或问题,请随时问我。 –
您能否详细说明这个方法与我在问题中提供的链接中的不同之处?粘贴一段代码并不是特别有用。 –
另外,'DropDownStyle'不是'DataGridViewComboBoxColumn'的属性。这是一个错字吗? –