Question

I have a Problem with addressing a button. I have many buttons in my program and I have a function which is used by every button. I'm getting the name of the last clicked button with this:

foreach (Control t in this.Controls)
{
    if (t.Focused)
    {
        ClickedButton = t.Name;
    }

}

Then I want to change the Text of the button:

ClickedButton.Text = "Whatever";

But I can't use ClickedButton as the name of the button.

Thank you in advance!

Was it helpful?

Solution

Assuming this is an event, you can just do something like this

Button btn = (Button)sender;
btn.Text = "Whatever";

OTHER TIPS

If you are writing this in your button_click event,

You can Get the button like this :

Button BTN = sender as Button;
BTN.Text = "This Button Has Been Clicked!";

If you're having the clicked button call into the Click event, you should have sender as an argument, which you can cast to a Button and get the name of the control.

Since you have the button reference, you could then also set the control's text.

protected void btnTest_Click(object sender, EventArgs e)
{
    Button b = sender as Button;
    if ((b != null) && (b.Name == "btnTest"))
    {
         b.Text = "yay";
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top