Dynamically create textbox and label at runtime – C#

Let’s see how we can create dynamically a panel and add two controls into it, a label and a textbox.

Panel panel = new Panel();
panel.Location = new System.Drawing.Point(30, 20);
panel.Name = "panel1";
panel.AutoSize = true;
panel.Size = new System.Drawing.Size(230, 20);
 
Label l = new Label();
l.AutoSize = true;
l.Location = new System.Drawing.Point(3, 5);
l.Name = "lbl1";
l.Size = new System.Drawing.Size(30, 15);
l.TabIndex = 1;
l.Text = "Label Text:";
panel.Controls.Add(l);
 
TextBox txt = new TextBox();
txt.Location = new System.Drawing.Point(l.Width + 10, 5);                            
txt.MaxLength = 100;
txt.Name = "txtbox1";
txt.Size = new System.Drawing.Size(200, 20);
txt.TabIndex = 2;
panel.Controls.Add(txt);
%d bloggers like this: