Reputation: 6480
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
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
Reputation: 32428
You have a few options.
button2_Click
from button1_click
(i advise against this one).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();
}
// 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);
}
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
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