Reputation: 37
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!
Upvotes: 0
Views: 940
Reputation: 13367
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";
}
}
Upvotes: 0
Reputation: 2163
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!";
Upvotes: 0
Reputation: 26068
Assuming this is an event, you can just do something like this
Button btn = (Button)sender;
btn.Text = "Whatever";
Upvotes: 2