Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

one Click event for multiple buttons with Text property

I want to make a click event for a bunch of buttons. The problem is that I want to use the button's Text, and pass it to a function. Now the click event is passed a object sender. When I tried changing that to Button sender, it gave errors. But I don't know how else I can work with the senders Text.

Here is the normal code, which gave a single error:

private void guess_Click(object sender, EventArgs e)
{
     guess(sender.Text);
}

I changed it to this, which gave errors:

private void guess_Click(Button sender, EventArgs e)
{
     guess(sender.Text);
}

Question: How can I work with the Button's Text property within this click event, which is a single click_event for multiple buttons?

like image 709
user2953063 Avatar asked Feb 04 '26 04:02

user2953063


1 Answers

Step 1: You need to subscribe to the Button Click event of all your buttons to the same EventHandler. so that button click on all your Buttons will fire the same `Event Handler.

Step 2: You need to cast the object sender into Button and then access its Text property to get the Button Text.

Try This:

button1.Click += new System.EventHandler(MyButtonClick);
button2.Click += new System.EventHandler(MyButtonClick);
button3.Click += new System.EventHandler(MyButtonClick);

private void MyButtonClick(object sender, EventArgs e)
{
  Button btnClick =  (Button)sender ;
  guess(btnClick.Text);
}
like image 169
Sudhakar Tillapudi Avatar answered Feb 05 '26 17:02

Sudhakar Tillapudi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!