Reputation: 8004
Here is the major jist of what i want this to do.
I have created two button in my Form Initializer As shown Below
public Form1()
{
InitializeComponent();
Button b1 = new Button();
b1.Parent = this;
b1.Name = "btnA";
b1.Text = "Button A";
b1.Click += new EventHandler(button_Click);
b1.Show();
Button b2 = new Button();
b2.Parent = this;
b2.Name = "btnB";
b2.Text = "Button B";
b2.Click += new EventHandler(button_Click);
b2.Show();
}
private void button_Click(object sender, EventArgs e)
{
MessageBox.Show("Button A or Button B was Clicked?");
}
I need to know which button has been clicked, and obviously manipulate that button that was clicked.
Even something like change the text of the Button that was clicked.
Im preaty sure that we can use the object sender to access the button from which the event was fired but just dont know how to use the sender to manipulate the correct button.
Any Direction or help will be apreciated thanks
Upvotes: 1
Views: 3504
Reputation: 8389
The sender object will give you the object that sent the message. You can cast it to a button.
var clickedButton = (Button) sender;
Upvotes: 0
Reputation: 56903
The sender
parameter is the object that raised the event:
Button button = sender as Button;
if( button != null )
{
MessageBox.Show("Button " + button.Name + " was clicked");
}
else
{
MessageBox.Show("Not a button?");
}
Upvotes: 1
Reputation: 1503639
Just cast sender
to Button
:
private void button_Click(object sender, EventArgs e)
{
Button clicked = (Button) sender;
MessageBox.Show("Button " + clicked.Name + " was Clicked.");
}
Upvotes: 4