Question

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.

Was it helpful?

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.
    }
}

OTHER TIPS

A disabled control will not fire a event. So two options are either always disable update the text then re-enable or create a derived class wrapper (using this method you could still do data binding)

class myClass : TextBox
{
    public virtual string TextWithoutEvents
    {
        get
        {

            return base.Text;
        }
        set
        {
            bool oldState = Enabled;
            Enabled = false;
            base.Text = value;
            Enabled = oldState;
        }
    }
}

If the user selects "Pilot name" from the list, you set the text box to "Pilot name". This will cause the list box to select "Pilot name". So the selection should be kept. You just have to break the recursion.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top