Welcome to WindowsClient.net | Sign in | Join

Here are some frequently asked questions about Windows Forms and their answers.

Windows Forms FAQs

How do I add a control to a Window Form at runtime?

There are three steps to adding a control at runtime.

Create the control.

Set control properties.

Add the control to the Form's Controls collection.

In general, if you need help on exactly what code you need to add, just look at the code generated by the Designer when you add the control at design time. You can usually use the same code at runtime.

This code fragment creates a TextBox at runtime.

[C#]

TextBox tb = new TextBox(); // step 1 

tb.Location = new Point( 10, 10 ); // step 2 
tb.Size = new Size( 100, 20 ); 
tb.Text = "I was created at runtime"; 

this.Controls.Add( tb ); // step 3 

[Visual Basic]

Dim tb as TextBox = New TextBox() ' step 1 

tb.Location = New Point(10, 10) ' step 2
tb.Size = New Size(100, 20) 
tb.Text = "I was created at runtime" 

Me.Controls.Add(tb) ' step 3

Contributed from George Shepherd's Windows Forms FAQ



Page view counter