Create User Interface Controls at Runtime

Visual studio provides a very rich tool box, useful to create nice UI, but what if we are in need create those controls at run time, sure we could , that's what I am going to demonstrate now.

Code behind the form

using System;

using System.Collections.Generic;
using
System.ComponentModel;
using
System.Data;
using
System.Drawing;
using
System.Linq;
using
System.Text;
using
System.Windows.Forms;

namespace CreateUserInterfaceControlsAt_RunTime

{
    public partial class Form1 :
Form

    {
        buttonCount = 0;
        int textBoxCount = 0;

        int ty = 100;

        int by = 100;
 

        public Form()

        {
            InitializeComponent();

        }

        private void button1_Click(object sender, EventArgs e)

        {

            by+=40;

            buttonCount++;

            Button b = new Button();

            b.Name = "MyButton" + buttonCount.ToString();

            b.Text = "MyButton" + buttonCount.ToString(); ;

            b.Size = new Size(100, 35);

             Point p = new Point(20, by);

            b.Location = p;

            this.Controls.Add(b);

        }
 
        private void button2_Click(object sender, EventArgs e)

        {

            ty += 20;

            textBoxCount++;

            TextBox tx = new TextBox();

            tx.Name = "MyTextBox" + textBoxCount.ToString();

            tx.Text = "MyTextBox" + textBoxCount.ToString(); ;

            tx.Size = new Size(100, 35);

            Point p = new Point(250, ty);

            tx.Location = p;

            this.Controls.Add(tx);

        }

    }

}


The UI

Image1.png

Let's explain the code, It is very simple :

  1. Create your instance of the wished control:

    Ex : Button b=new Button() ;
     
  2. Then give it it's property values: name, location..
     
  3. And the key is to add it to the form to be shown: this.Controls.Add(b)