0

I have a search text box on my WPF Windows. Whenever, the user presses enter key after writing some query in the textBox, the process should start.

Now, I also have this Search button, in the event of which I perform all this process.

So, for a texBox:

<TextBox x:Name="textBox1" Text="Query here" FontSize="20" Padding="5" Width="580" KeyDown="textBox1_KeyDown"></TextBox>

private void queryText_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Return)
            {
                //how do I fire the button event from here?
            }
        }
Cipher
  • 5,894
  • 22
  • 76
  • 112
  • see this post http://joshsmithonwpf.wordpress.com/2007/03/09/how-to-programmatically-click-a-button/ or this answer http://stackoverflow.com/a/7551766/273200 – Bala R Feb 24 '12 at 05:18

4 Answers4

1

It is possible but rather move your search logic into a method such as DoSearch and call it from both locations (text box and the search button).

Philip Fourie
  • 111,587
  • 10
  • 63
  • 83
0

Are you talking about manually invoking buttonSearch_onClick(this, null);?

Jason
  • 6,878
  • 5
  • 41
  • 55
0

You can Create a Common Method to do search for ex

public void MySearch()
{
     //Logic
}

Then Call it for diffetnt places you want like...

private void queryText_KeyDown(object sender, KeyEventArgs e)
     {
         if (e.Key == Key.Return)
         {
                      MySearch();
         }
     }

private void buttonSearch_onClick(object sender, EventArgs e)
{
     MySearch();
}
Ankesh
  • 4,847
  • 4
  • 38
  • 76
0

A event can not be fired/raised from outside the class in which it is defined.(Using reflection you can definitely do that, but not a good practice.)

Having said that, you can always call the button click event handler from the code as simple method call like below

private void queryText_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Return)
    {
        OnSearchButtonClick(SearchButton, null);
    }
}
Maheep
  • 5,539
  • 3
  • 28
  • 47