Creating Controls Dynamically (i.e. at Runtime)



To create any control dynamically we need to perform three  steps

Step1:- Creating object for respective control class
Syntax: - ClassName ObjectName =new ClassName ( );
Example: - TextBox T1=new TextBox ( );

Step2: -  Setting the required properties to the object
Syntax: - ObjectName.PropertyName=value;
Example :- T1.BackColor=Color.Red;
                   T1.ForeColor=Color.Yellow
                   T1.Left=90;
                   T1.Top=99;


Step3: - Adding this object to the controls collection of Form class
Syntax: -this.Controls.Add(ObjectName);
Example: - this.Controls.Add(T1);



Example with Dynamic Controls:-

Add a new Form i.e.,Form2 to the Windows Application WABasics
Create one Button Control & set the following properties to It

button1:

     Text      :         Sample
     Name     :         btnSample

Design :-



 Generate the btnSample Click Event
& write the following code in Source[Form2.cs] 

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 WABasics
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        private void btnSample_Click(object sender, EventArgs e)
        {
            Label L1 = new Label();
            L1.Left = 100;
            L1.Top = 100;
            L1.Text = "Enter Any Data";
            this.Controls.Add(L1);
            TextBox T1 = new TextBox();
            T1.Left=200;
            T1.Top=100;
            this.Controls.Add(T1);
        }
    }
}




Result :-



 

No comments:

Post a Comment