Learn how to a build a cloud-first strategyRegister Now


Retreive Values From Dynamically Created Textboxes

Posted on 2011-09-08
Medium Priority
Last Modified: 2012-06-21
I'm building a page that generates textboxes based on values retreived from a database.  It creats a dynamic amount of textboxes that the end user then fills out. I am having a difficult time retreiving these values on the server side click event of a asp button. Once i can get at the values on the server side event i can insert the values to the database.

Attached is some code showing how I am creating the textboxes:

If anyone can explain (or point out an article) how to reterive these values on the serverside button click event it would be greatly appreciated.


While objReader.Read()
                Dim tempRow As New TableRow()
                            Dim tempCell As New TableCell()
                            Dim tempTextBox As New TextBox()
                            tempTextBox.ID = "intReturned" + CStr(i)
                            tempTextBox.ClientIDMode = UI.ClientIDMode.Static
                            tempTextBox.MaxLength = 3
                            tempTextBox.Width = 36
                            tempTextBox.Style.Add("Text-Align", "Center")
                            tempTextBox.TabIndex = i
                i += 1
            End While

Open in new window

Question by:Zeuss_09

Expert Comment

ID: 36507199
You can find the controls by name. Not sure of the VB.NET syntax, but it should look something like this in C#:

for (int i = 0; i < controlCount; i++)
	TextBox txt = (TextBox)Page.Form.FindControl("intReturned" + i.ToString());
	Response.Write(txt.Text + "<br />");

Open in new window

LVL 10

Expert Comment

ID: 36507348
During a postback, asp.net completely creates a new instance of the page.  Part of what this means is that the only controls that are a part of the page's control collection by default, are the controls that were added to the page during design-time.  When you dynamically add a control, you are adding the control to the page's control collection during run-time.  After the page has been fully created and the html generated from the page has been sent to the client, the memory on the server is flushed, and the server has no recollection of any controls created during run-time.

That being said, the values of your controls (dynamically created or not) are all stored in ViewState in a name/value hash.

To access these values, you will need to recreate your controls using the exact same names and add them to the page's control collection, so that the asp.net engine will be able to properly map the values from ViewState to their associated controls.  The proper time to recreate your dynamic controls is during the Page_PreInit() event, which runs prior to ViewState being applied to the page's control collection.

Author Comment

ID: 36507799
Re-creating the controls are also proving to be diffucult as the number of text boxes are chosen by a drop down list on the page and the list items of this text box are also created dynamically and pulled from the database.

When the page tries to recreate the textboxes in pre init it can't get the info from the drop down list because it doesn't exist yet.

I'm wondering if it would be easier to post this page to a processing page that can determine the values from a post method?
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

LVL 11

Expert Comment

ID: 36507814
If one adds controls dynamically to a page and wants to get their information after PostBack, one needs to recreate these elements after the PostBack. Let's consider the following idea: First you create some controls:

   for(int i=0;i<10;i++) {
      TextBox objBox = new TextBox();
      objBox.ID = "objBox" + i.ToString();

After PostBack, you want to retrieve the text entered in the third TextBox. If you try this:

   String strText = objBox2.Text;

you'll receive an exception. Why? Because the boxes have not been created again and the local variable objBox2 simply not exists.

How to retrieve the Box?

You'll need to recreate the box by using the code above. Then, you may try to get its value by using the following code:

   TextBox objBox2;
   objBox2 = this.Page.FindControl("objBox2") as TextBox;
   if(objBox2 != null)
LVL 10

Expert Comment

ID: 36508247
What about storing the data from the selected option in the dynamically created dropdownlist in the database?
When the user selects an option from the dropdownlist you can fire off an ajax call to store the value in the database, then when you do a full postback, simply look up that value during Page_PreInit() and you can determine what all textboxes you need to create.

Author Comment

ID: 36516946
It blows me away that doing this is more diffucult in asp.net than it was in traditional ASP.

P1ST0LPETE You do have an interesting suggestion but it seem to add a degree of complexity that I'd rather avoid.

At this point I'm open to different options that allows me to accomplish this:

1) Populate a design time drop down list with run time values from a database

2) Upon user selection of the drop down list populate a table with labels and textboxes of which are pulled from the database based upon the selection from the drop down list

3) The user will alter the values of all the textboxes

4) The user will then click the submit button at which time all the text boxes need to be looped thru and saved to the daabase

If this explination isn't descriptive enough I can post the entire source code.

LVL 10

Accepted Solution

P1ST0LPETE earned 2000 total points
ID: 36517858
Check out this example.  This is using the UpdatePanel, which is the build in ajax in asp.net web forms.

Html Markup:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1.Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server" />
        <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true" OnSelectedIndexChanged="DropDownList_SelectedIndexChanged" />
        <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
                <asp:Panel ID="Panel1" runat="server" />
                <asp:AsyncPostBackTrigger ControlID="DropDownList1" />
        <asp:Button ID="SaveButton" runat="server" Text="Save" OnClick="SaveForm" />

Open in new window

Code Behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1
    public partial class Default : System.Web.UI.Page
        protected void Page_PreInit(object sender, EventArgs e)
            int index = Convert.ToInt32(Session["SelectedIndex"]);

            if (index > 0)

        protected void Page_Load(object sender, EventArgs e)
            if (!IsPostBack)

        protected void DropDownList_SelectedIndexChanged(object sender, EventArgs e)
            Session["SelectedIndex"] = this.DropDownList1.SelectedIndex;

        protected void SaveForm(object sender, EventArgs e)
            string text = ((TextBox)this.FindControl("Textbox1")).Text;

        private void DropDownList_Populate()
            for (int i = 1; i < 6; i++)
                this.DropDownList1.Items.Add(new ListItem("Option " + i));

        private void CreateDynamicTable(int index)
            TableCell cell1 = new TableCell();
            Label label = new Label();
            label.Text = "Enter Text";
            label.ID = "Label1";

            TableCell cell2 = new TableCell();
            TextBox textbox = new TextBox();
            textbox.ID = "Textbox1";

            TableRow row = new TableRow();

            Table table = new Table();


Open in new window

However, based on what you said above "It blows me away that doing this is more diffucult in asp.net than it was in traditional ASP."
If you are just now switching from ASP Classic, man I would highly advise using ASP.NET MVC instead of ASP.NET Web Forms.  I did ASP.NET Web Forms for a number of years, and about 6 months ago I switched to MVC.  Dynamic controls among so many other things are so much easier to deal with in MVC, and the code is more cleaner too.
LVL 19

Expert Comment

by:Amandeep Singh Bhullar
ID: 37909731
This question has been classified as abandoned and is closed as part of the Cleanup Program. See the recommendation for more details.

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I have developed many web applications with asp & asp.net and to add and use a dropdownlist was always a very simple task, but with the new asp.net, setting the value is a bit tricky and its not similar to the old traditional method. So in this a…
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
this video summaries big data hadoop online training demo (http://onlineitguru.com/big-data-hadoop-online-training-placement.html) , and covers basics in big data hadoop .
Please read the paragraph below before following the instructions in the video — there are important caveats in the paragraph that I did not mention in the video. If your PaperPort 12 or PaperPort 14 is failing to start, or crashing, or hanging, …
Suggested Courses

810 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question