views:

32

answers:

3

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.

A: 

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.

dtb
True, however, it's a no-go in this case. The user will occasionally tap through results using the arrow keys, and the ListBox selects every item as they go.
Anders
A: 

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.
    }
}
Jerod Houghtelling
I ended up using a combination of your answer and Scott's answer:private void listBoxPilot_SelectionChanged(object sender, SelectionChangedEventArgs e){textBoxPilot.IsEnabled = false;Member selectedPilot = (Member)listBoxPilot.SelectedItem;textBoxPilot.Text = selectedPilot.firstName;textBoxPilot.IsEnabled = true;}private void textBoxPilot_TextChanged(object sender, TextChangedEventArgs e){ if (textBoxPilot.IsEnabled == false) return; [search stuff]}This eliminates the need for a new global variable. Thanks to both of you.
Anders
A: 

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;
        }
    }
}
Scott Chamberlain
Thanks for the inspiration. In the end, I used a combination of your answer and Jerod's answer; see my reply to his post.
Anders