简体   繁体   中英

C# multiple events on a single button click?

I'm new to C# have been learning it slowly for a couple of weeks and i know some basic JavaScript.

I wan't to make three buttons change the value of a string or int to different values at the different buttons, then start a common event that all buttons share. I know I can copy and paste them but I want to make the code short.

protected void btn1_Click(object sender, EventArgs e)
{
   string example = a;
   //Start the MainEvent
}
protected void btn2_Click(object sender, EventArgs e)
{
   string example = b;
   //Start the MainEvent
}
protected void btn3_Click(object sender, EventArgs e)
{
   string example = c;
   //Start the MainEvent
}
protected void MainEvent(object sender, EventArgs e)
{
    //Content of MainEvent. Result of MainEvent is determined by the value of "Example".
}

You can do it using only one event handler:

btn1.Click += MainEvent;
btn2.Click += MainEvent;
btn3.Click += MainEvent;

protected void MainEvent(object sender, EventArgs e)
{
    string example;
    if(sender == btn1)
    {
        example = a
    }
    else if(sender == btn2)
    {
        example = b
    }
    else if(sender == btn3)
    {
        example = c
    }

    //Do whatever with example
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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