Marvin Retro
Marvin Retro

Reputation: 35

Clicked 2 Button At Once

Hello :) I Actually want to ask something So my aim here is "If I click the button 1, the button 2 will be clicked too "

"Is it possible ? Click a one button so the other button will be clicked ?"

Here is my Code:

Button btn1 = sender as Button;

if (btn1 == button1){
    button2.PerformClick();
}

It actually does not work it seems there is something wrong

Upvotes: 1

Views: 50

Answers (3)

Shenron
Shenron

Reputation: 453

Unless you have a weird reason for doing this, don't!

You should prefer something like this :

void button1_Click(object sender, EventArgs e)
{
    DoWork1();
    DoWork2();
}

void button2_Click(object sender, EventArgs e)
{
    DoWork2();
}

Upvotes: 1

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

I suggest extracting methods.

Before:

private void button1_Click(object sender, EventArgs e)
{
  Routine 1 code ...
  Routine 2 code ... // <- do not copy yourself; copy + paste is evil!
}

private void button2_Click(object sender, EventArgs e)
{
  Routine 2 code ...
}

After:

//TODO: think over the right name
private void Routine1() 
{ 
  Routine 1 code ...
}

//TODO: think over the right name 
private void Routine2() 
{ 
  Routine 2 code ...
}

...

private void button1_Click(object sender, EventArgs e)
{
  Routine1();
  Routine2();
}

private void button2_Click(object sender, EventArgs e)
{
  Routine2();
}

Upvotes: 2

Vandita
Vandita

Reputation: 748

It is very simple.

   private void button1_Click(object sender, EventArgs e)
    {
        if ((sender as Button) == button1)
        {
            button2_Click(sender, e);
        }
    }

    private void button2_Click(object sender, EventArgs e)
    {

    }

Upvotes: 1

Related Questions