How can I add a control to a Window Form at runtime

Platform: WinForms| Category: Controls

To add a control at runtime, you do three steps:

  • 1. Create the control
  • 2. Set control properties
  • 3. 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 generally use the same code at runtime.

Here are code snippets that create a textBox at runtime.

[C#]
	//step 1
	TextBox tb = new TextBox();

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

	//step3
	this.Controls.Add(tb);

[VB.NET]

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

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

	’step3
	Me.Controls.Add(tb)

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.