sean
sean

Reputation: 9258

Creating Dynamic ComboBox in C#

I'm new to Visual Studio 2010 C# and I'm creating an application where the user will select the number of textboxes will be shown in a form. For example, if the user will select "2" automatically there will be 2 boxes will be shown in the form.

This is the screenshots that I want to create.

Select number of textboxes to be shown

The output when the user select 2

Upvotes: 1

Views: 3535

Answers (2)

Nikola Radosavljević
Nikola Radosavljević

Reputation: 6911

I guess what you need to know is dynamic creation of controls. To do what you want here you need to:

  • Create a control
  • Add control to form
  • Set control location, size and anything else you need

It would go something like this:

Texbox texbox = new Textbox();
Controls.Add(textbox);
textbox.Top = 20;
textbox.Left = 200;
textbox.Width = 200;
textbox.Name = "textbox1";

So that there's something left for you to do, you should repeat steps above in a loop, and calculate location of each textbox so that they're not stacked up.

Upvotes: 3

Dulini Atapattu
Dulini Atapattu

Reputation: 2735

comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    int i = 0;  
    int y = 0;
    while (i < int.Parse(comboBox1.SelectedItem.ToString()))
    {
        System.Windows.Forms.TextBox tt = new System.Windows.Forms.TextBox();
        y = y + 30;
        tt.Location = new System.Drawing.Point(0, y);
        this.Controls.Add(tt);
        i++;
    }
}

Hope this helps

Upvotes: 1

Related Questions