Create Form TextBox Controls at Runtime

Sometimes you might want to create a user control at run-time.  These are times when you are not sure of what controls to include during the form designing phase of your program.  What we usually do is to draw all available controls in the designer form. Then at run-time we simply make the controls invisible leaving us with workable visible controls. But there is a better method. What should be done is exactly illustrated below. You should write code to draw the controls at run-time. You should draw the controls when needed to save memory.


Creating controls at runtime can be very useful if you have some conditions that you might want to satisfy before displaying a set of controls. You might want to display different controls for different situations. CSharp provides an easy process to create them. If you look carefully in the Designer.cs file of any form, you will find codes that initiate the creation of controls. You will see only some properties set, leaving other properties default. And this is exactly what we will do here. We write code behind the Form that creates the controls with some properties that we set & others that are simply set to their default value by the Compiler.

The main steps to draw controls are summarized below:
  • Create/Define the control or Array of controls
  • Set the properties of the control or individual controls in case of Arrays
  • Add the control/s to the form or other parent containers such as Panels
  • Call the Show() method to display the control

The code below shows how to draw controls:

namespace Create.Controls.At.Runtime
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            TextBox[] tb = new TextBox[7];
            for (int i = 0; i <= 6; i++)
            {
                tb[i] = new TextBox();
                tb[i].Width = 150;
                tb[i].Left = 20;
                tb[i].Top = (30 * i) + 30;
                tb[i].Text = "Text Box Number: " + i.ToString();
                this.Controls.Add(tb[i]);
                tb[i].Show();
            }
        }
    }
}
Custom Search