How do I get the "item Selected" event with autocomplete in C #?

I have a code using 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 the "selected item" after the user selects the autocomplete suggestion? And the value of the field?

+5


source to share


4 answers


There is no such thing as the selected Event element for the textbox, which I believe you use for autocomplete. What you can do is add a key down event to your text block. There you can check if the enter key was pressed (clicking on the suggested link is the same as pressing the enter key). Something like that:



private void textBox1_KeyDown(object sender, KeyEventArgs e) {
    if (e.KeyData == Keys.Enter) {
        String selItem = this.textBox1.Text;
    }
}

      

+7


source


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 on the toolbar and compare the contents of the toolbar, then fire an event if they match what the delegate will receive.

+1


source


Instead of focusing on detecting if an item has been selected from the autocomplete list, you should instead check if the current value of the textbox is in the autocomplete recordset .

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 the exact string that falls into the autocomplete list of values ​​- OR - they select that value from the autocomplete list - should that lead to different behavior? I think in most cases it shouldn't be.

+1


source


It depends a little on the situation and workflow of your program, but I have an example where I run a combo box out of focus check. And then I check if the selected value is part of the collection:


private void cmbt1Name1_LostFocus(object sender, RoutedEventArgs e)
{
        ComboBox cmb = sender as ComboBox;
        FillFivePoints(cmb);
}
private void FillFivePoints(ComboBox usedCombobox)
{
    if (txtSerial.AutoCompleteCustomSource.Contains(t.Text))
    {
    ...

      

0


source







All Articles