HelpNeeder
HelpNeeder

Reputation: 6480

Using event from button 1 in button 2

I have 2 buttons. I am trying to use event from button 1 into button 2 so they both do the same thing.
So by clicking 2, button 1 get clicked also. I am doing this actually from menu strip item but I suppose it has the same principle. I just don't want to have duplicated code. I thought that button1.Click() would work, but apparently it doesn't. How could I do this?

Simplified example:

private void button1_Click(object sender, EventArgs e)
{
    count += 1;
    label1.Text = Convert.ToString(count);
}
private void button2_Click(object sender, EventArgs e)
{
    count += 1;
    label1.Text = Convert.ToString(count);
}

-- EDIT --

I am using a class diagram which doesn't show any additional methods that would/should do this. Need to stick to the class diagram.

Upvotes: 1

Views: 1657

Answers (3)

Guy
Guy

Reputation: 5528

Whatever button1 does put in a separate method, and call that method from both buttons, it is better to separate the code and then you don't duplicate anything.

What you offered creates an unnatural dependency between the buttons that should not exist.

About your class diagram, if it is a private method then it should not matter.

Upvotes: 2

George Duckett
George Duckett

Reputation: 32428

You have a few options.

  1. Put the code that's in both events into its own method and call that.
  2. Make a single _click method and set it as both button's event handler.
  3. You could call button2_Click from button1_click (i advise against this one).

1

private IncrementAndDisplay()
{
    count += 1;
    label1.Text = Convert.ToString(count);
}
private void button1_Click(object sender, EventArgs e)
{
    IncrementAndDisplay();
}
private void button2_Click(object sender, EventArgs e)
{
    IncrementAndDisplay();
}

2

// Change both button's clicked events to use this method in the IDE, or in code.
private void button_Click(object sender, EventArgs e)
{
    count += 1;
    label1.Text = Convert.ToString(count);
}

3

private void button1_Click(object sender, EventArgs e)
{
    button2_Click(sender, e); // Bad!
}
private void button2_Click(object sender, EventArgs e)
{
    count += 1;
    label1.Text = Convert.ToString(count);
}

Upvotes: 7

Widor
Widor

Reputation: 13275

You should use a separate function/method to handle the action and then have both button handlers call that function:

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

private void doTheThing()
{
    count += 1;
    label1.Text = Convert.ToString(count);
}

Upvotes: 1

Related Questions