Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How get Event "item Selected" with AutoComplete in C#?

I have code using an AutoCompleteStringCollection:

    private void txtS_TextChanged(object sender, EventArgs e)
    {
        TextBox t = sender as TextBox;
        string[] arr = this.dbService.GetAll();

        if (t != null)
        {
            if (t.Text.Length >= 3)
            {
                AutoCompleteStringCollection collection = new AutoCompleteStringCollection();
                collection.AddRange(arr);                    
                this.txtSerial.AutoCompleteCustomSource = collection;
            }
        }
    }

How can I get the event for "item selected" after user selects an AutoComplete suggestion? And value of field?

like image 264
viton-zizu Avatar asked Oct 30 '14 00:10

viton-zizu


Video Answer


3 Answers

There's no such thing as chosen item Event for a textBox, which I believe you're using for the AutoComplete. What you could do is add a key down event to your textBox. There you could verify if the enter key was pressed (clicking on a suggested link is the same as pressing enter). Something like that:

private void textBox1_KeyDown(object sender, KeyEventArgs e) {
    if (e.KeyData == Keys.Enter) {
        String selItem = this.textBox1.Text;
    }
}
like image 127
actaram Avatar answered Oct 22 '22 10:10

actaram


Rather than focusing on detecting if an item from the autocomplete list was selected, instead you should check if the current value of the textbox is in the set of autocomplete entries.

if (txtSerial.AutoCompleteCustomSource.Contains(t.Text))
{
    // Logic to handle an exact match being selected
    ...
}
else
{
    // Update the autocomplete entries based on what was typed in
}

If the user typed in an exact string which happens to be be within the list of autocomplete values -- OR -- they select that value from the autocomplete list -- should this produce any different behavior? I think that in most cases it should not.

like image 31
StayOnTarget Avatar answered Oct 22 '22 12:10

StayOnTarget


Short answer: make a custom event

Long answer: You can intercept the KeyDown event of your textbox for numpad Enter or normal Enter and the mouse doubleclick event of the toolbox and compare the content of the toolbox then fire an event if they match that a delegate will pick up.

like image 1
Mystra007 Avatar answered Oct 22 '22 10:10

Mystra007