您可能会发现,使用textbox控件内置的自动完成功能更为简单,而不是试图自己为所有可能的场景编写代码。
有两个重要的特性
TextBox
必须配置以启用其自动完成功能的控件:
AutoCompleteMode
和
AutoCompleteSource
.
这个
AutoCompleteMode
属性允许您选择
怎样
文本框自动完成功能将生效。你可以在
AutoCompleteMode
values
None Disables the automatic completion feature for the ComboBox and TextBox controls.
Suggest Displays the auxiliary drop-down list associated with the edit control. This drop-down is populated with one or more suggested completion strings.
Append Appends the remainder of the most likely candidate string to the existing characters, highlighting the appended characters.
SuggestAppend Applies both Suggest and Append options.
这个
AutoCompleteSource
属性允许您指定希望文本框建议自动完成的字符串。在您的情况下,您可能需要指定
CustomSource
,这要求您设置
AutoCompleteCustomSource
属性设置为用户定义的字符串方法集合,如“Apple、Ball、…”等。
这个
DataGridViewTextBoxColumn
简单地承载一个标准
文本框
控件,因此它提供的所有自动完成功能都已免费提供给您。您可以通过处理
EditingControlShowing
你的事件
DataGridView
,就像这样:
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
//Create and fill a list to use as the custom data source
var source = new AutoCompleteStringCollection();
source.AddRange(new string[] {"Apple", "Ball"});
//Set the appropriate properties on the textbox control
TextBox dgvEditBox = e.Control as TextBox;
if (dgvEditBox != null)
{
dgvEditBox.AutoCompleteMode = AutoCompleteMode.Suggest;
dgvEditBox.AutoCompleteCustomSource = source;
dgvEditBox.AutoCompleteSource = AutoCompleteSource.CustomSource;
}
}
编辑:
如果您希望保持与原始文本框示例中相同的行为,可以
处理
TextChanged
事件
DataGridViewTextBox列
. 正如我上面已经解释过的
DataGridViewTextBox列
简单地承载一个标准
文本框
控件,因此为其
事件
事件并使用以前的相同代码:
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
TextBox dgvEditBox = e.Control as TextBox;
if (dgvEditBox != null)
{
//Add a handler for the TextChanged event of the underlying TextBox control
dgvEditBox.TextChanged += new EventHandler(dgvEditBox_TextChanged);
}
}
private void dgvEditBox_TextChanged(object sender, EventArgs e)
{
//Extract the textbox control
TextBox dgvEditBox = (TextBox)sender;
//Insert the appropriate string
if (dgvEditBox.Text.Length == 1)
{
if (dgvEditBox.Text == "B" || dgvEditBox.Text == "b")
{
dgvEditBox.Text = "Ball";
}
}
}