2014-05-10 73 views
1

我在我的win應用程序中有2個按鈕。當我點擊c中的另一個按鈕時如何調用按鈕點擊事件#

Button1的做一個任務:

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++; 
    } 
} 

按鈕2做以下

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; 
} 

我只是想只使用一個按鈕兩個事件。

但我想在按鈕1調用的事件之前調用button2的事件。

意思是我想用一個按鈕代替按鈕1和2,當我點擊我想要做的第一件事就是在文本框中獲取列表框項目。

{ 
    foreach (string item in listBox2.Items) 
     textBox7.Text += item.Contains("@") ? string.Format("{0}#", item.Split('@')[0]) : string.Empty; 
} 

然後事件開始進度條和關閉連接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++; 
} 
+1

一個很好的解決方案將被提取功能集成到方法,並調用裏面的方法按鈕處理程序。這樣你就不需要點擊click事件,而是調用一個方法。維護也很容易。 – pasty

+1

@pasty非常感謝你 –

回答

5

我建議從點擊事件成單獨的方法去除背後邏輯。

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(); 
} 

根據我的經驗,這樣更容易維護和測試。有不同控制的事件互相呼叫會使遵循邏輯更加困難。

+0

它是我找到/謝謝你寶貴的答案的最佳途徑。 –

1

您可以手動觸發的Button2單擊事件:

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

萬一你neen事件:

Button1.click += method1; 
Button1.click += method2; 


void method1(object sender, EventArgs e) 
{ 
    // do your stuff 
} 
void method2(object sender, EventArgs e) 
{ 
    // do your stuff 
} 
1

您可以使用PerformClick按鈕對象的方法

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) 
    { 
     /* .................... */ 
    }