ASPSnippets

Alerts
Get notified when a new article is published.

Name
 
Email

Your email will always be private and will not be shared.

Follow us on twitter.
 
Creating Dynamic TextBox Controls in ASP.Net
Author Name: Mudassar Khan Published Date: June 13, 2009
Filed Under :
ASP.Net
Views: 12934

In this article I will explain how to create dynamic TextBox control in asp.net. I will also explain how to retain value across postbacks and also how to recreate the controls on each postback. In addition I will explain how to dynamically attach event handlers to TextBox control in asp.net


Creating Dynamic TextBoxes in ASP.Net



To start with I added a PreInit event to the Page and added the following snippet in it

C#

Panel pnlTextBox;

protected void Page_PreInit(object sender, EventArgs e)

{

    //Create a Dynamic Panel

    pnlTextBox = new Panel();

    pnlTextBox.ID = "pnlTextBox";

    pnlTextBox.BorderWidth = 1;

    pnlTextBox.Width = 300;

    this.form1.Controls.Add(pnlTextBox);

 

    //Create a LinkDynamic Button to Add TextBoxes

    LinkButton btnAddtxt = new LinkButton();

    btnAddtxt.ID = "btnAddTxt";

    btnAddtxt.Text = "Add TextBox";

    btnAddtxt.Click += new System.EventHandler(btnAdd_Click);

    this.form1.Controls.Add(btnAddtxt);

   

    //Recreate Controls

    RecreateControls("txtDynamic", "TextBox");

}

 

VB.Net

Protected Sub Page_PreInit(ByVal sender As Object, ByVal e As EventArgs) Handles Me.PreInit

  'Create a Dynamic Panel

  pnlTextBox = New Panel()

  pnlTextBox.ID = "pnlTextBox"

  pnlTextBox.BorderWidth = 1

  pnlTextBox.Width = 300

  Me.form1.Controls.Add(pnlTextBox)

 

  'Create a LinkDynamic Button to Add TextBoxes

  Dim btnAddtxt As New LinkButton()

  btnAddtxt.ID = "btnAddtxt"

  btnAddtxt.Text = "Add TextBox"

  AddHandler btnAddtxt.Click, AddressOf btnAdd_Click

  Me.form1.Controls.Add(btnAddtxt)

 

  'Recreate Controls

  RecreateControls("txtDynamic", "TextBox")

End Sub


As you will notice above I have created the following controls

1 Dynamic panel pnlTextBox and added it to the form control on the page

2. Dynamic LinkButton btnAddTxt attached a Click event btnAdd_Click to it and added to the form control.

3. A function called RecreateControls is being called which I’ll explain later in the article

 

On the Click event of the dynamic LinkButton I have added the following event

C#

protected void btnAdd_Click(object sender, EventArgs e)

{

    int cnt = FindOccurence("txtDynamic");

    CreateTextBox("txtDynamic-" + Convert.ToString(cnt + 1));

}

 

VB.Net

Protected Sub btnAdd_Click(ByVal sender As Object, ByVal e As EventArgs)

    Dim cnt As Integer = FindOccurence("txtDynamic")

    CreateTextBox("txtDynamic-" & Convert.ToString(cnt + 1))

End Sub

 

As you will notice I am calling two functions

1. FindOccurence

2. CreateTextBox

 

The FindOccurence function as the name suggests gets the occurrence of the Dynamic TextBox in the Request.Form collection. The basic idea is that I have given ID is a common pattern that is all IDs are of the form txtDynamic e.g. txtDynamic-1, txtDynamic-2 and so on.

 

C#

private int FindOccurence(string substr)

{

    string reqstr = Request.Form.ToString();

    return ((reqstr.Length - reqstr.Replace(substr, "").Length)

                      / substr.Length);

}


VB.Net

Private Function FindOccurence(ByVal substr As String) As Integer

   Dim reqstr As String = Request.Form.ToString()

   Return ((reqstr.Length - reqstr.Replace(substr, "").Length) & _

                                           / substr.Length)

End Function

 

Now the CreateTextBox as the name suggests is used to create dynamic TextBox. The function accepts ID as parameter

C#

private void CreateTextBox(string ID)

{

    TextBox txt = new TextBox();

    txt.ID = ID;

    txt.AutoPostBack = true;

    txt.TextChanged += new EventHandler(OnTextChanged);

    pnlTextBox.Controls.Add(txt);

 

    Literal lt = new Literal();

    lt.Text = "<br />";

    pnlTextBox.Controls.Add(lt);

}

 

VB.Net

Private Sub CreateTextBox(ByVal ID As String)

    Dim txt As New TextBox()

    txt.ID = ID

    txt.AutoPostBack = True

    AddHandler txt.TextChanged, AddressOf OnTextChanged

    pnlTextBox.Controls.Add(txt)

 

    Dim lt As New Literal()

    lt.Text = "<br />"

    pnlTextBox.Controls.Add(lt)

End Sub

 

As you will notice I am creating a new TextBox and adding Items to it. Once done that I am attaching TextChanged Event Handler and setting the AutoPostBack property to true. Finally I am adding it to the panel pnlTextBox.

    

The SelectedIndexChanged Event Handler is given below.

C#

protected void OnTextChanged(object sender, EventArgs e)

{

    TextBox txt = (TextBox)sender;

    string ID = txt.ID;

    ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert",

                 "<script type = 'text/javascript'>alert('" + ID  +

                  " fired OnTextChanged event');</script>");

   

    //Place the functionality here

}


VB.Net

Protected Sub OnTextChanged(ByVal sender As Object, ByVal e As EventArgs)

    Dim txt As TextBox = DirectCast(sender, TextBox)

    Dim ID As String = txt.ID

 

    'Place the functionality here

    ClientScript.RegisterClientScriptBlock(Me.GetType(), _

    "Alert", "<script type = 'text/javascript'>alert('" & ID _

    & " fired OnTextChanged event');</script>")

End Sub

 

In the above event I am finding the ID of the caller TextBox based by Type Casting the Sender parameter and then firing a JavaScript alert to notify which TextBox fired the event as shown in figure below


Dynamic TextBox TextChanged Event Handler attached to the Dynamic TextBox



Now the most important function is RecreateControls whose job is to recreate all the TextBox on each postback

 

       

C#

private void RecreateControls(string ctrlPrefix, string ctrlType)

{

    string[] ctrls = Request.Form.ToString().Split('&');

    int cnt = FindOccurence(ctrlPrefix);

    if (cnt > 0)

    {

        for (int k = 1; k <= cnt; k++)

        {

            for (int i = 0; i < ctrls.Length; i++)

            {

                if (ctrls[i].Contains(ctrlPrefix + "-" + k.ToString())

                    && !ctrls[i].Contains("EVENTTARGET"))

                {

                    string ctrlID = ctrls[i].Split('=')[0];

 

                    if (ctrlType == "TextBox")

                    {

                        CreateTextBox(ctrlID);

                    }

                    break;

                }

            }

        }

    }

}

 

 

VB.Net

Private Sub RecreateControls(ByVal ctrlPrefix As String, ByVal ctrlType As String)

  Dim ctrls As String() = Request.Form.ToString().Split("&"c)

  Dim cnt As Integer = FindOccurence(ctrlPrefix)

  If cnt > 0 Then

      For k As Integer = 1 To cnt

         For i As Integer = 0 To ctrls.Length - 1

             If ctrls(i).Contains((ctrlPrefix & "-") + k.ToString()) _

                  AndAlso Not ctrls(i).Contains("EVENTTARGET") Then

                 Dim ctrlID As String = ctrls(i).Split("="c)(0)

 

                 If ctrlType = "TextBox" Then

                      CreateTextBox(ctrlID)

                 End If

                 Exit For

             End If

         Next

     Next

  End If

End Sub

 

As you will notice above I first find the occurrence of a particular string here txtDynamic in the Request.Form collection and then I loop through each item and keep adding the TextBox using the CreateTextBox function described earlier.

This completes the article download the sample code in VB.Net and C# using the link below

DynamicTextBoxes.zip (3.95 kb)


<< Creating Dynamic DropDownList Controls in ASP.Net


If you like this article, help us grow by bookmarking this page on any social bookmarking site.
Bookmark and Share Page copy protected against web site content infringement by Copyscape

Related Articles

Comments

Leandro said:
I would like know if is possible identify the value of textbox to save this in database.
February 22, 2010  

Mudassar Khan said:
Reply To: Leandro
You can find the controls and their values
using FindControl
this.form1.FindControl("TextBox1")
February 22, 2010  

S Nair said:
Hi MAKbr br I have a panel placed in .aspx page. Want to add controls into it.br In your case you creating panel also but am not. Adding control is working but when i going for adding next control its not working. Its always shows only one control. How to handle this..br
April 26, 2010  

Mudassar Khan said:
Reply To: S Nair
Hi Suthish,
Make sure that you are not clearing the controls in panel each time you are adding a textbox.
If you do that each time old controls will get removed
April 26, 2010  

rams said:
i tried the code with dropdownlist. and ofcourse changed the code where necessary. but the dropdownlist control add only first time. and doesnt add further on to the page. on debug i found that the request.form collection is not redering the details of dropdown. however its fine with textbox. any idea anyonebr thanx to all
May 07, 2010  

Mudassar Khan said:
Reply To: rams
Refer my article

http://www.aspsnippets.com/Articles/Creating-Dynamic-DropDownList-Controls-in-ASP.Net.aspx
May 07, 2010  

Dharmendra Kumar said:
Its nice thing u implemented br br Thanking you lotsbr Regardsbr Dharmendra kumarbr
July 03, 2010  

Add Comments

You can add your comment about this article using the form below. Make sure you provide a valid email address
else you won't be notified when the author replies to your comment

Please note that all comments are moderated and will be deleted if they are
  • Not relavant to the article
  • Spam
  • Advertising campaigns or links to other sites
  • Abusive content.
There is no need to add BR tags. Simply press enter for new line

Name*  
Email*
Comment*  
Security code
Security code