DotNetCurry Logo

Creating controls at runtime using Windows Forms 2.0

Posted by: Suprotim Agarwal , on 1/26/2008, in Category WinForms & WinRT
Views: 30105
Abstract: In this article, we will explore how to add controls to a form at runtime. We will also explore how to bind events to these runtime controls.
Creating controls at runtime using Windows Forms 2.0
 
In this article, we will explore how to add controls to a form at runtime. We will also explore how to bind events to these runtime controls.
Many a times, in our projects, we are in a situation where a control needs to be created at runtime. One example I could think of is a person filling in his family details is given the choice to enter the number of members in his family. In this case, we cannot determine how many family members will be entered by the user. So we have to accept the number of members and then generate those many textboxes. In this article, I will demonstrate you how to create controls at runtime and also bind events to these controls.
Step 1: Create a new project. File > New > Project. In the Project Type pane, select your language (Visual C# or Visual Basic) and then select ‘Windows Application’ in the ‘Visual Studio installed templates’ pane.
Step 2:  Type a name for the project  ‘CreateRuntimeControls’ and click OK.
Step 3: Declare two variables of type TextBox and Button at the class level in Form1.
C#
public partial class Form1 : Form
    {
        // Create controls at runtime.
        TextBox txtRun = null;
        Button btnRun = null;
 
        public Form1()
        {
            InitializeComponent();
        }
   }
 
VB.NET
Public Partial Class Form1
      Inherits Form
            ' Create controls at runtime.
            Private txtRun As TextBox = Nothing
            Private btnRun As Button = Nothing
 
            Public Sub New()
                  InitializeComponent()
            End Sub
End Class
Step 4: Double click on Form1 and in the Form1_Load() event write this code:
C#
private void Form1_Load(object sender, EventArgs e)
        {
            // Initialize the text box control and add it to the form
            txtRun = new TextBox();
            txtRun.Name = "txtDynamic";
            txtRun.Location = new System.Drawing.Point(20, 18);
            txtRun.Size = new System.Drawing.Size(200, 25);
            // Add the textbox control to the form's control collection
            this.Controls.Add(txtRun);
 
            // Initialize the button control and add it to the form
            btnRun = new Button();
            btnRun.Location = new System.Drawing.Point(20, 44);
            btnRun.Size = new System.Drawing.Size(100, 25);
            btnRun.Text = "Click Me";
            // Add the button control to the form's control collection
            this.Controls.Add(btnRun);
            // Bind the button to an event handler
            btnRun.Click += new System.EventHandler(DisplayText);
        }
VB.NET
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs)
                  ' Initialize the text box control and add it to the form
                  txtRun = New TextBox()
                  txtRun.Name = "txtDynamic"
                  txtRun.Location = New System.Drawing.Point(20, 18)
                  txtRun.Size = New System.Drawing.Size(200, 25)
                  ' Add the textbox control to the form's control collection
                  Me.Controls.Add(txtRun)
 
                  ' Initialize the button control and add it to the form
                  btnRun = New Button()
                  btnRun.Location = New System.Drawing.Point(20, 44)
                  btnRun.Size = New System.Drawing.Size(100, 25)
                  btnRun.Text = "Click Me"
                  ' Add the button control to the form's control collection
                  Me.Controls.Add(btnRun)
                  ' Bind the button to an event handler
                  AddHandler btnRun.Click, AddressOf DisplayText
 End Sub
In the above code, we are creating controls and specifying some control properties like Name, Location and Size. The control is then added to the form’s control collection. This step is important for the control to be visible on the form.
In order to bind the button to an event handler, we use new System.EventHandler(DisplayText). You can mention any method instead of ‘DisplayText’. The code for DisplayText will look as mentioned below:
C#
private void DisplayText(object sender, System.EventArgs e)
        {
            if (txtRun != null)
            {
                txtRun.Text = "I was created dynamically";
            }
        }
VB.NET
Private Sub DisplayText(ByVal sender As Object, ByVal e As System.EventArgs)
                  If Not txtRun Is Nothing Then
                        txtRun.Text = "I was created dynamically"
                  End If
 End Sub
That’s it. Run the form. You will see that the textbox and button control have been generated at runtime. On clicking the button, the textbox is populated with the text ‘I was created dynamically’.
Having understood how to create controls dynamically, you can now experiment and try and create new controls on the button click. Try out the family member example I stated in the beginning of the article. Accept the number at runtime and create textboxes to fill in the family member’s name.
I hope this article was useful and I thank you for viewing it.
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+
Further Reading - Articles You May Like!
Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and a new one recently at The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for nine times in a row now. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that represents premium web sites and digital publications comprising of Professional web, windows, mobile and cloud developers, technical managers, and architects.

Get in touch with him on Twitter @suprotimagarwal, LinkedIn or befriend him on Facebook



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by abhi singh on Wednesday, February 6, 2008 4:24 AM
gr8 article.........!!
Comment posted by vivek on Tuesday, July 15, 2008 3:27 AM
good one!!!
Comment posted by vinay kumar.D on Thursday, November 6, 2008 6:55 AM
This example help me alot, how to add an event to dynamically created control
Comment posted by Abhishek Patel on Monday, January 11, 2010 4:09 AM
Hi, this example really helped me a lot. I also have one another question I am dynamically creating a KeyDown event of textbox:
t[i].KeyDown += new KeyEventHandler(IsNumber);

in which i am calling a method called IsNumber:

private void IsNumber(object sender, EventArgs e)

Here I would like to check whether the key pressed a numeric or not for which i have to use e.KeyValue property. which i am not able to do so and i got the following error:

Error   2   'System.EventArgs' does not contain a definition for 'KeyValue' and no extension method 'KeyValue' accepting a first argument of type 'System.EventArgs' could be found (are you missing a using directive or an assembly reference?)

can you please help me out with this problem.

Thank You,
Abhishek