问题描述:

 btnName1 = new Button();

counter++;

//Start setting of Button

btnName1.Location = new Point(47, 35 + a);

btnName1.Size = new Size(132, 59);

btnName1.FlatStyle = FlatStyle.Popup;

btnName1.Text = textBox1.Text;

btnName1.Name = "btn" + counter.ToString();

btnName1.BackColor = Color.White;

btnName1.ForeColor = Color.Black;

panel1.Controls.Add(btnName1);

a += btnName1.Size.Height + 2;

btnName1.Click += BtnName1_Click;

I wrote this code for making a new button. When I click on add button this code runs and by each click on add button we can make new button.

But my problem is this

How can I set click handle for each button? I mean when I click on each button, they show their text to me

and I wrote this code to make the texts different:

btnName1.Text = textBox1.Text;

网友答案:

You didn't post your event code, but as Steve mentioned in his comment (that appears to have since been removed), you can use the sender argument to get the particular button that was clicked. Something like the following should be what you're after:

private void BtnName1_Click(object sender, EventArgs e)
{
    //Access the text with: (sender as Button).Text

    //Example: Write this button's text to the debug output window
    Debug.WriteLine((sender as Button).Text);
}  

Just be careful that in my specific example, you're only subscribing a Button to this event.

网友答案:

Prefered way is what you've put so far

btnName1.Click += BtnName1_Click;

...

private void BtnName1_Click(object sender, EventArgs e) { 
  // Button which has been clicked 
  Button button = sender as Button;
  //TODO: put relevant code here
  ...
}

However, you can assign to each button its own event handler:

btnName1.Click += (s, e) => {
  Button button = s as Button;
  //TODO: put relevant code here
  ...
};
相关阅读:
Top