Friday, May 31, 2013

How to Create Dynamic Control in ASP.Net

Leave a Comment
Sometimes in ASP.NET situation arise where you need to create web controls dynamically by writing the code in the code behind file. In this tutorial I will  create text box controls dynamically and bind data to text box controls from array at runtime. You can create any .net controls at runtime based on the reference of this tutorial. For that you need to create instance of the class whom controls you want to create. As I am creating text box control so I will create the instance of TextBox class and then use Add method of Form class to create text box control dynamically as shown  in picture below:

textbox controls in

Sample Code to Create Text Box Controls at Runtime Dynamically:

Code in C#:

Add Web Form and put the following  code in code behind file:
Import Namespace:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

protected void Page_Load(object sender, EventArgs e)
    protected void Bind_Text_Box()
        string[] user_name = new string[] {"Manish","Ajit Kumar","Rohit Mian","Deepak Sharma" };

        for (int i = 0; i < 4; i++)
            TextBox txt1 = new TextBox();
            txt1.ID = "txtname" + i;
            txt1.Text = user_name[i];


Code in VB.NET:

Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.Web.UI

Imports System.Web.UI.WebControls

     Protected Sub Page_Load(sender As Object, e As EventArgs)
    End Sub

Protected Sub Bind_Text_Box()
        Dim user_name As String() = New String() {"Manish", "Ajit Kumar", "Rohit Mian", "Deepak Sharma"}

        For i As Integer = 0 To 3
            Dim txt1 As New TextBox()
            txt1.ID = "txtname" & i
            txt1.Text = user_name(i) 

    End Sub


Post a Comment