Ralt
Ralt

Reputation: 2206

Triggering a button click through code

So I have the following code for when the "Add player" button is clicked

private void addPlayerBtn_Click_1(object sender, EventArgs e)
{
    //Do some code
}

I want to trigger this code from my SDK however. Here is what I have tried

private void command()
{       
    addPlayerBtn_Click_1(object sender, EventArgs e);          
}

I get lots of errors as soon as I put in the line

 addPlayerBtn_Click_1(object sender, EventArgs e) 

Could somebody please tell me how to write the code so that I can trigger an event by just writting it in code?

Upvotes: 19

Views: 72308

Answers (6)

Majed Leader
Majed Leader

Reputation: 41

private void command()
 {     
   addPlayerBtn.PerformClick();
 }

Upvotes: 4

Steve Wellens
Steve Wellens

Reputation: 20638

You are not using the sender or the events so you can call the function directly like this:

addPlayerBtn_Click_1(null, null);

Upvotes: 2

ispiro
ispiro

Reputation: 27743

addPlayerBtn_Click_1(null, null);

This works if you don't need the information in sender and e.

Upvotes: 2

gdoron
gdoron

Reputation: 150313

addPlayerBtn_Click_1(object sender, EventArgs e);

Should be:

addPlayerBtn_Click_1(this, new EventArgs());

Upvotes: 2

Ben Voigt
Ben Voigt

Reputation: 283901

When you call a function, you provide actual arguments, which are values, not formal arguments, which are types and parameter names.

Change

addPlayerBtn_Click_1(object sender, EventArgs e);

to

addPlayerBtn_Click_1(addPlayerBtn, EventArgs.Empty);

Upvotes: 7

Dave Zych
Dave Zych

Reputation: 21897

For one, when calling a method, you don't declare the type of the parameter, just the value.

So this:

addPlayerBtn_Click_1(object sender, EventArgs e);

Should be

addPlayerBtn_Click_1(sender, e);

Now, you'll have to declare sender and e. These can be actual objects, if you have event args to pass, or:

addPlayerBtn_Click_1(null, EventArgs.Empty);

The above can be used in either WinForms or ASP.NET. In the case of WinForms, you can also call:

addPlayerBtn.PerformClick();

Upvotes: 36

Related Questions