Adding dynamically elements on the win form?

I have two forms. Clicking button on form1 opens form2 where user adds details and this is returned back to form1, information is stored to List and TextBoxes and other elements of interface are created.

I have 5 tabs for different levels but information added is the same.

How can I avoid creating similar code 5 times using

if (level==5) {//do this whole code again}

Example of element added:

int _nextTextBoxTop=15;
List<TextBox> CodesMy = new List<TextBox>();

var code = new TextBox();
CodesMy.Add(code);
code.Location = new Point(12, _nextTextBoxTop);
_nextTextBoxTop += 36;
code.Size = new Size(80, 25);
code.Text = mcode;
tabPageLevel5.Controls.Add.Controls.Add(code); 

Upvotes: 2

Views: 5163

Answers (2)

Servy
Servy

Reputation: 203815

You shouldn't be specifying the positions absolutely. Create a FlowLayoutPanel and just add each new textbox (or usercontrol with all of the controls that represent the new "thing" to add) to that panel so that they get added just below the previous one.

The FlowLayoutPanel that you add them to can vary depending on which Tab you want to add them to. You can make it a parameter to a method, similar to Paul's suggestion, or you can have a variable currentTab, panelInCurrentTab or something like that which is set appropriately, and then a method that simply adds the new controls to that container.

Upvotes: 1

Paul Sasik
Paul Sasik

Reputation: 81537

The simplest solution could be to refactor your element creation into a separate function like this:

CreateControls(TabPage tabPage)
{
var code = new TextBox();
CodesMy.Add(code);
code.Location = new Point(12, _nextTextBoxTop);
_nextTextBoxTop += 36;
code.Size = new Size(80, 25);
code.Text = mcode;
tabPage.Controls.Add.Controls.Add(code);     
}

Your client code would then look like:

if (level==5) {CreateControls(tabPageLevel5);}

A simpler way than dynamically adding controls could be to create a user control that is used on each of your tab pages.

Even if you need to add controls dynamically you could still do it with a user control and clone it each time per each additional tab page.

Upvotes: 2

Related Questions