Click here to Skip to main content
15,880,967 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i have to added user control dynamically in vertical position based on user input. suppose i have pass 3 in textbox then user control add 3 times. when click on button

What I have tried:

private void button1_Click(object sender, EventArgs e)
           string a = textBox1.Text;
           int h = Convert.ToInt32(a);

           for (int i = 0; i <= h; ++i)
               var b = new MyUserControl1
                 Size = new Size(1000, 25),
                   // Location = new Point(150 + i * 150, 150),
                   Location = new Point(100, 50 + 60 * i),//arrange verically
                  // Location = new Point(200, 35 + (i * 100),
                 Text = string.Format("MyUserControl{0}", i)
               b.Click += MyUserControl;
Updated 11-Jul-21 21:45pm

1 solution

Firstly, don't use Convert methods on user input - they throw an exception if teh user makes a mistake. Which makes your app crash ...
For numeric inputs use the appropriate TryParse methods:
int h;
if (!int.TryParse(textBox1.Text, out h))
   ... report problem to user ...
Or better, use a NumericUpDown control instead so they can't enter a "bad value".

Secondly, do yourself a favour, and stop using Visual Studio default names for everything - you may remember that "TextBox8" is the mobile number today, but when you have to modify it in three weeks time, will you then? Use descriptive names - "tbMobileNo" for example - and your code becomes easier to read, more self documenting, easier to maintain - and surprisingly quicker to code because Intellisense can get to to "tbMobile" in three keystrokes, where "TextBox8" takes thinking about and 8 keystrokes...

Thirdly, we have no idea what you expected that code to do, or what it does that you didn't expect - remember that we can't see your screen, access your HDD, or read your mind - we only get exactly what you type to work with and we can't run that code in isolation as we have no access to your control or the click event handler.
There are however far too many "magic numbers" in teher for my taste...
Share this answer

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