【问题标题】:Set the other fields when user selects a correct Autocomplete option for a textbox当用户为文本框选择正确的自动完成选项时设置其他字段
【发布时间】:2023-03-25 06:36:01
【问题描述】:

我在 winform 中有一个 TextBox,并将 TextBox 的 AutoCompleteSource 设置为 CustomSource。现在的问题是相应地设置表单中的其他字段,用户从自动完成列表中选择一个选项。
例如,我的自动完成列表包含"foo", "food", "foomatic"。当用户键入'f' 时,会显示所有三个选项。用户选择"foo"。表单中的下一个文本框也会相应更改。如何做到这一点。

提前致谢。

【问题讨论】:

  • 你在TextChanged事件中没有得到那个吗?
  • TextChanged 每次用户输入新字符时都会触发事件。但我想在用户最终选择一个选项时捕获事件。
  • 那你可以选择ValidatingValidated 但我认为你将不得不失去焦点

标签: c# .net winforms autocomplete


【解决方案1】:

当您沿着自动完成列表移动时,文本框会触发“向下”箭头键的键事件;它还将所选项目文本设置为文本框。您可以跟踪向下键来设置其他字段。

或者,您可以捕获“Enter”键的键事件,如果用户按 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);
}

【讨论】:

  • 这个解决方案不是我想要的,但确实是一个好方法。
【解决方案2】:

我使用 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);

现在,即使选择的值仅来自自动完成弹出窗口,也会触发该事件。 (不管是用鼠标还是键盘选择)

【讨论】:

    猜你喜欢
    • 2011-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多