Reputation: 97
I have 2 buttons in my win app.
Button1 do a task :
private void button1_Click(object sender, EventArgs e)
{
progressBar1.Value = 0;
String[] a = textBox7.Text.Split('#');
progressBar1.Maximum = a.Length;
for (var i = 0; i <= a.GetUpperBound(0); i++)
{
ansh.Close();
progressBar1.Value++;
}
}
Button 2 do following
private void button2_Click(object sender, EventArgs e)
{
foreach (string item in listBox2.Items)
textBox7.Text += item.Contains("@") ? string.Format("{0}#", item.Split('@')[0]) : string.Empty;
}
I just want to use just one button for two events.
But I want the event of button2 to be called before event that was called by button1.
Means I want to use just one button instead of button 1 and 2.and when I click I want first thing to be done is getting listbox items in a textbox.
{
foreach (string item in listBox2.Items)
textBox7.Text += item.Contains("@") ? string.Format("{0}#", item.Split('@')[0]) : string.Empty;
}
and then the event of starting progress bar and closing connection x.
progressBar1.Value = 0;
String[] a = textBox7.Text.Split('#');
progressBar1.Maximum = a.Length;
for (var i = 0; i <= a.GetUpperBound(0); i++)
{
ansh.Close();
progressBar1.Value++;
}
Upvotes: 5
Views: 21511
Reputation: 157
You can use PerformClick method of button object
Button button1 = new Button(), button2 = new Button();
button1.Click += new EventHandler(button1_Click);
button2.Click += new EventHandler(button2_Click);
void button1_Click(object sender, EventArgs e)
{
/* .................... */
button2.PerformClick(); //Simulate click on button2
/* .................... */
}
void button2_Click(object sender, EventArgs e)
{
/* .................... */
}
Upvotes: 14
Reputation: 499
Just in case you neen events:
Button1.click += method1;
Button1.click += method2;
void method1(object sender, EventArgs e)
{
// do your stuff
}
void method2(object sender, EventArgs e)
{
// do your stuff
}
Upvotes: 2
Reputation: 66439
I'd suggest removing the logic from behind the click events into separate methods.
private void MethodOne()
{
progressBar1.Value = 0;
String[] a = textBox7.Text.Split('#');
progressBar1.Maximum = a.Length;
for (var i = 0; i <= a.GetUpperBound(0); i++)
{
ansh.Close();
progressBar1.Value++;
}
}
private void MethodTwo()
{
foreach (string item in listBox2.Items)
textBox7.Text += item.Contains("@") ? string.Format("{0}#", item.Split('@')[0]) : string.Empty;
}
private void button1_Click(object sender, EventArgs e)
{
MethodTwo();
MethodOne();
}
private void button2_Click(object sender, EventArgs e)
{
MethodTwo();
}
In my experience, it's easier to maintain and test this way. Having different controls' events all calling each other makes it tougher to follow the logic.
Upvotes: 7
Reputation: 101681
You can trigger the click event of Button2
manually:
private void button1_Click(object sender, EventArgs e)
{
button2_Click(sender,e);
...
}
Upvotes: 3