How to execute click event on dynamically created button in C # .net

I am trying to create an application where the user can select a category and according to it displays their subcategories, these subcategories are buttons that are dynamically created.

Now when the buttons are dynamically created, I am confused how to write code on the button_click event as I don't know how many subcategories there are.

So, is there any way I can execute a click event on a specific button so that I can execute specific commands?

EDITED

This is the code I tried

Button btnDynamicButton = new Button();

private void btnclick_Click(object sender, EventArgs e)
{
label2.Text = btnDynamicButton.Text;
}
private void btnappetizer_Click(object sender, EventArgs e)
{
 groupBox2.Visible =false;
 DataTable dt = new DataTable();
 dt = itemmasterbl.SelectallrecordFromtblItem(btnappetizer.Text);
 for (int i = 0; i < dt.Rows.Count; i++)
 {
  string name = "Appetizer" + DynamicButtonCount;
  Button btnDynamicButton1 = new Button();
  btnDynamicButton1.Name = name;
  btnDynamicButton1.Text = name;
  btnDynamicButton1.Size =
  new System.Drawing.Size(150, 30);
  btnDynamicButton1.Location =
  new System.Drawing.Point(180, DynamicButtonCount * 30);
  btnDynamicButton1.Click +=new EventHandler(btnclick_Click);<br>
  Controls.Add(btnDynamicButton1);
  DynamicButtonCount++;
  btnDynamicButton = btnDynamicButton1;
  }
 }

      

Once I do that, it creates three buttons according to the number of values ​​in the DB of the itemmaster under appetite, but as soon as I click on any of the three buttons, only the last button text is shown on the label, because on the last line I have:

btnDynamicButton = btnDynamicButton1;

Which information will be displayed last, but I want whatever button I click should display the appropriate text. How can I achieve this.

+3


source to share


1 answer


you can put all your logic in one handler:

System.Windows.Forms.Button b = new System.Windows.Forms.Button();
b.Click += new EventHandler(b_Click);
//finally insert the button where it needs to be inserted.
...

void b_Click(object sender, EventArgs e)
{
    MessageBox.Show(((System.Windows.Forms.Button)sender).Name + " clicked");
}

      

To your edit:



You keep the link for your button (s) inside the box btnDynamicButton

. Hence, it is always overwritten with the last button you created. You shouldn't link to a button using a field. The sender

click handler parameter contains the button element that was clicked. See the above code: Simple drop sender

before Button

and you know which button was pressed:

private void btnclick_Click(object sender, EventArgs e)
{
   Button btn = (Button)sender
   label2.Text = btn.Text;
}

      

+5


source







All Articles