我在winform中有一个TextBox,并将TextBox的AutoCompleteSource
设置为CustomSource
。现在的问题是相应地设置表单中的其他字段,用户从自动完成列表中选择一个选项。
例如,我的自动完成列表包含"foo", "food", "foomatic"
。当用户键入'f'
时,将显示所有三个选项。用户选择"foo"
。并且表单中的下一个文本框会相应更改。如何做到这一点。
提前致谢。
答案 0 :(得分:1)
当您沿着自动完成列表向下移动时,文本框会触发“向下”箭头键的键事件;它还将选定的项目文本设置为文本框。您可以跟踪向下键以设置其他字段。
或者,您可以捕获“Enter”键的键事件,如果用户按下回车键或鼠标单击选择列表中的项目,则会引发该键事件
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
//Check if the Text has changed and set the other fields. Reset the textchanged flag
Console.WriteLine("Enter Key:" + textBox1.Text);
}
else if (e.KeyCode == Keys.Down)
{
//Check if the Text has changed and set the other fields. Reset the textchanged flag
Console.WriteLine("Key Down:" + textBox1.Text);
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
//this event is fired first. Set a flag to record if the text changed.
Console.WriteLine("Text changed:" + textBox1.Text);
}
答案 1 :(得分:1)
我使用ComboBox来获得此选项:
// Create datasource
List<string> lstAutoCompleteData = new List<string>() { "first name", "second name", "third name"};
// Bind datasource to combobox
cmb1.DataSource = lstAutoCompleteData;
// Make sure NOT to use DropDownList (!)
cmb1.DropDownStyle = ComboBoxStyle.DropDown;
// Display the autocomplete using the binded datasource
cmb1.AutoCompleteSource = AutoCompleteSource.ListItems;
// Only suggest, do not complete the name
cmb1.AutoCompleteMode = AutoCompleteMode.Suggest;
// Choose none of the items
cmb1.SelectedIndex = -1;
// Every selection (mouse or keyboard) will fire this event. :-)
cmb1.SelectedValueChanged += new EventHandler(cmbClientOwner_SelectedValueChanged);
现在,即使仅从“自动完成”弹出窗口中选择了值,也会触发该事件。 (如果使用鼠标或键盘进行选择无关紧要)