1

My program creates buttons dynamically.

private void CreateButton(string buttonName)
{

   Color[] c = { Color.Red, Color.Teal, Color.Blue, Color.WhiteSmoke };

   transbutton = new Button();
   transbutton.BackColor = c[2];
   transbutton.Text = buttonName;
   transbutton.Name = buttonName + "Button";
   transbutton.Width = 150;
   transbutton.Height = 150;
   transbutton.Font = new Font("Segoe UI", 13);
   transbutton.ForeColor = Color.White;

   transbutton.Click += new EventHandler(transbutton_Click);
}

private void transbutton_Click(object sender, EventArgs e)
{

   tbList.Text = transbutton.Text;
}

enter image description here

What I am trying to do is when the user clicks on the button(s) it adds the name of the button into the multiline TextBox such as in the picture above. I created an EventHandler but cant figure it out how to make it work with dynamic buttons.

1
  • Are you adding your buttons to the screen/form? (I don't see a call in your code) Commented May 2, 2013 at 20:41

2 Answers 2

7

You have a reference to the button that was clicked right there as the sender argument. So...

private void transbutton_Click(object sender, EventArgs e)
    {
       tbList.Text += "\r\n" + ((Button)sender).Text;
    }
Sign up to request clarification or add additional context in comments.

1 Comment

It works with anything that fires an event (all windows and web controls, for example). The sender argument is always the object that fired the event, so you can always cast it to its original type and use its properties ;)
0

use button array like this.it will create 3 dynamic buttons bcoz h variable has value of 3

public void button_Click(object sender, EventArgs e)
{
 if( sender == buttonArray[0] )
  {


  MessageBox.Show("hello");
   }

 }

private void button1_Click(object sender, EventArgs e)
{

    int h =3;


    Button[] buttonArray = new Button[8];

    for (int i = 0; i <= h-1; i++)
    {
       buttonArray[i] = new Button();
       buttonArray[i].Size = new Size(20, 43);
       buttonArray[i].Name= ""+i+"";
       buttonArray[i].Click += button_Click;//function
       buttonArray[i].Location = new Point(40, 20 + (i * 20));
        panel1.Controls.Add(buttonArray[i]);

    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.