Click here to Skip to main content
15,897,273 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,
I want to create controls in runtime, say i want to create
10 buttons & when each button clicked, calls function .
i used:

Button btn = new Button();
btn.Text = "Click Me";
btn.Click += new System.EventHandler(button_click);
Panel1.Controls.Add(btn);


it works but i want some thing like loop to create all ten buttons.

Thanks
Posted
Updated 28-Feb-11 3:46am
v2
Comments
Albin Abel 28-Feb-11 9:50am    
why don't put the above code in a loop up to ten?. Add the loop increment counter to the button name. Then in the button click function check the sender's name and execute the approptiate logic.
Sandeep Mewara 28-Feb-11 10:02am    
So, whats the issue?

1 solution

Try:
for (int i = 0; i < 10; i++)
   {
   Button btn = new Button();
   btn.Text = "Click Me" + i.ToString();
   btn.Top = i * 20;
   btn.Click += new System.EventHandler(button_click);
   Panel1.Controls.Add(btn);
   }


[edit]Moved the ending tag out of the method... - OriginalGriff[/edit]
 
Share this answer
 
v2
Comments
Sergey Alexandrovich Kryukov 28-Feb-11 11:00am    
Simple as that, my 5.
(Well, I understand this is only a simple example, but btn.Top should be something "like i * btn.Height + verticalGap")
--SA
OriginalGriff 28-Feb-11 11:12am    
I know, I know! I only put that bit in so that they wouldn't be on top of each other and the OP could see them... :laugh:
Sergey Alexandrovich Kryukov 1-Mar-11 3:28am    
That's why I voted 5 anyway, assuming you simply didn't care :-)
--SA

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