Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# How to set button text of different buttons to the same textbox

I have a couple of buttons and a textbox. I want to make it so that when I press button1 the text from the textbox goes to button and when I press button2 the text goes to button2 and so on. I now have this:

protected void Button1_Click(object sender, EventArgs e)
    {

        Button1.Text = TextBox1.Text;
    }

    protected void Button2_Click(object sender, EventArgs e)
    {
        Button2.Text = TextBox1.Text;
    }

    protected void Button3_Click(object sender, EventArgs e)
    {
        Button3.Text = TextBox1.Text;
    }

Edit: Is there a shorter way to do this?

like image 652
Aiko Avatar asked Mar 07 '23 23:03

Aiko


1 Answers

If you point the Click event for each button to the same method you can have this in one method like so;

protected void Button_Click(object sender, EventArgs e)
{
    ((Button)sender).Text = TextBox1.Text;
}

You can change the method that is used for a button event in the designer by clicking on the button, going to the Properties window and clicking on the little lightening symbol for events and selecting the Button_Click method for the Click event.

like image 197
DiskJunky Avatar answered Apr 06 '23 13:04

DiskJunky