Search code examples
c#eventstextboxtextchanged

How to determine whether TextChanged was triggered by keyboard in C#?


I have a method

private void textBoxPilot_TextChanged(object sender, TextChangedEventArgs e)
{ ... }

where the textbox in question takes a search string from the user and populates a ListBox with the results on every keystroke.

Subsequently, when an item is picked from the ListBox, I would like the choice reflected in the same Textbox. However, I don't want to trigger the search mechanism, which would cause the Listbox to forget its selection.

How can I determine whether the TextChanged event was triggered by the user (via they keyboard or maybe copy/paste) or by another method using textBoxPilot.Text = "Pilot name";?

Thanks.


Solution

  • bit of a hack, but....

    public class MyForm : Form
    {
        private bool _ignoreTextChanged;
    
        private void listView1_SelectionChanged( object sender, EventArgs e )
        {
           _ingnoreTextChanged = true;
           textBoxPilot.Text = listView1.SelectedValue.ToString(); // or whatever
        }
    
        private void textBoxPilot_TextChanged( object sender, TextChangedEventArgs e )
        {
           if( _ignoreTextChanged )
           {
               _ignoreTextChanged = false;
               return;
           }
    
           // Do what you would normally do.
        }
    }