Which object was clicked when the event was fired?

This is the main point of what I want to do.

I have created two buttons 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 was clicked and obviously manipulate the button that was clicked.

Even something like changing the text of the button clicked on the button.

Im preaty sure we can use an object sender to access the button from which the event was fired, but just don't know how to use the sender to control the correct button.

Any direction or help would be appreciated thanks

+1


a source to share


3 answers


Just click sender

on Button

:



private void button_Click(object sender, EventArgs e)
{
    Button clicked = (Button) sender;
    MessageBox.Show("Button " + clicked.Name + " was Clicked.");
}

      

+4


a source


The parameter sender

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?");
}

      

+1


a source


The sender object will give you the object that sent the message. You can overlay it on a button.

var clickedButton = (Button) sender;

      

0


a source







All Articles