Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to trigger a button click in my code? [duplicate]

Tags:

c#

windows-8

How can I trigger a button click directly in my code?

I have a code like this:

namespace App1
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            // fire a click ebent von the "Button" MyBtn
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            // ...
        }
    }
}

Is it possible to fire a click event von the button MyBtn? If yes how?

I know I can call the Button_Click method, but I want to call it over the button.

something like: MyBtn.FireClickEvent();

like image 609
gurehbgui Avatar asked May 28 '13 12:05

gurehbgui


2 Answers

You can trigger the Button_Click event from the code as follows:

MyBtn.PerformClick();

You can try this one also:

MyBtn.Click(new object(), new EventArgs());
like image 89
Santosh Panda Avatar answered Sep 30 '22 12:09

Santosh Panda


You can remove the method link to your event(Click) :

MyBtn.Click -= new EventHandler(Button_Click);

And add an other method :

MyBtn.Click += new EventHandler(FireClickEvent);

So, when you will click the button, the method "FireClickEvent" will be called instead of "Button_Click".

To perform a click in the code :

MyBtn.PerformClick();
like image 34
Vinc 웃 Avatar answered Sep 30 '22 14:09

Vinc 웃