开发者

Set the other fields when user selects a correct Autocomplete option for a textbox

I have a TextBox in a winform and have set the AutoCompleteSource of the TextBox as开发者_运维技巧 CustomSource. Now the problem is to set the other fields in the form accordingly a user selects an option from the auto complete list.

For example my auto complete list contains "foo", "food", "foomatic". When a user types 'f' all the three options are shown. User selects "foo". And the next text box in the form changes accordingly. How to accomplish this.

Thanks in advance.


The textbox fires key events for "Down" arrow key when you travel down the auto complete list; it also sets the selected item text to the textbox. You can track the down key to set the other fields.

Alternatively, you can capture the key events for "Enter" key, which is raised if the user selects an item in the list pressing the enter key or mouse click

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);
}


I've used ComboBox to gain this option:

    // 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);

now, the event is fired on value selected even if it's only from the Autocomplete popup window. (doesn't matter if the selection done with mouse or keyboard)

Set the other fields when user selects a correct Autocomplete option for a textbox

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜