Click here to Skip to main content
15,996,470 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hello friends
sorry for my poor English.
this is my question :
i have a form .i create dynamically 5 buttons into the form.(in the flowLayoutPanel1)
i want when i click every button it's text or name be appeared on a label1.
i want to do by sender button.
this is my code: (it do not work)
C#
public void addbutton_dynam_Click(object sender, EventArgs e)
{
    counter += 1;
    Button btnAdd = new Button();
    this.Text = counter.ToString();
    btnAdd.Name = "click";
    btnAdd.BackColor = Color.Gray;
    btnAdd.Text = "Add";
    btnAdd.Location = new System.Drawing.Point(20, 20);

    flowLayoutPanel1.Controls.Add(btnAdd);

}

code is for when i click ...
C#
public void click(object sender)
{
    Button btn = (Button)sender;
    this.label1.Text = (btn.Name + " pressed");

}

pls help.
Posted
Updated 16-Apr-13 9:23am
v3

1 solution

You need to add a click event handler to the button - or the event handler method is not called.
C#
    Button btnAdd = new Button();
    this.Text = counter.ToString();
    btnAdd.Name = "click";
    btnAdd.Click += new EventHandler(btnAdd_Click);
    btnAdd.BackColor = Color.Gray;
    btnAdd.Text = "Add";
    btnAdd.Location = new System.Drawing.Point(20, 20);

    flowLayoutPanel1.Controls.Add(btnAdd);
    }

void btnAdd_Click(object sender, EventArgs e)
    {
    Button btn = (Button)sender;
    if (btn != null)
        {
        label1.Text = (btn.Name + " pressed");
        }
    }
Note the check for null in the handler - it's worth always adding this. You can use the same method with a variety of controls and checking stops it throwing a null reference exception.
 
Share this answer
 
Comments
mahmoodof 16-Apr-13 15:24pm    
thank you.
OriginalGriff 16-Apr-13 15:30pm    
You're welcome!
Maciej Los 16-Apr-13 15:28pm    
+5

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900