简体   繁体   中英

How to make buttons display their text in a label using one click event

Is it possible to have a click event that displays the text of buttons in a label in c#.

I want to write single code that will work for:

public button1_Click(Object sender, EventArgs e){ 
   label1.Text = button1.Text; 
}

public button2_Click(Object sender, EventArgs e){ 
   label2.Text = button2.Text;
}

Is this what you are looking for?

On a button click, you can handle setting text as below you can add two buttons. Have same click events for both buttons. Take help of parameter sender to get which button is clicked.

code (sender as Button) gives you all the details of clicked button.

 private void button1_Click(object sender, EventArgs e)
    {
        this.label1.Text = (sender as Button).Text;
    }

1) Add a Button and a Label to the blank Form in a new project.

2) Double-click the Button.

This will generate the following Click event method...

private void button1_Click(object sender, EventArgs e) {

}

3) Put the following line of code in the button1_Click method body:

label1.Text = button1.Text;

4) Profit.

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