0

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!

Matt
  • 22,721
  • 17
  • 71
  • 112
Philipp Thi
  • 37
  • 2
  • 7

3 Answers3

2

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

Button btn = (Button)sender;
btn.Text = "Whatever";
Kevin DiTraglia
  • 25,746
  • 19
  • 92
  • 138
0

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";
    }
}
Writwick
  • 2,133
  • 6
  • 23
  • 54
Lynn Crumbling
  • 12,985
  • 8
  • 57
  • 95
0

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!";
Writwick
  • 2,133
  • 6
  • 23
  • 54