繁体   English   中英

当我单击C#中的另一个按钮时如何调用按钮单击事件

[英]How to call a button click event when i click another button in c#

我的赢应用程序中有2个按钮。

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

我只想将一个按钮用于两个事件。

但是我希望在由button1调用的事件之前调用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++;
}

我建议将点击事件背后的逻辑删除为单独的方法。

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

以我的经验,以这种方式进行维护和测试更加容易。 由于控件的事件互不相同,因此很难遵循逻辑。

您可以使用按钮对象的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)
    {
        /* .................... */
    }

您可以手动触发Button2的click事件:

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

以防万一您需要进行以下事件:

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


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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM