Retreive Values From Dynamically Created Textboxes

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.

ML


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
                            tempCell.Controls.Add(tempTextBox)
                            tempRow.Cells.Add(tempCell)
                Table1.Rows.Add(tempRow)
                i += 1
            End While

Open in new window

Zeuss_09Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

yesthatbobCommented:
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


0
P1ST0LPETECommented:
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.
0
Zeuss_09Author Commented:
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?
0
Exploring ASP.NET Core: Fundamentals

Learn to build web apps and services, IoT apps, and mobile backends by covering the fundamentals of ASP.NET Core and  exploring the core foundations for app libraries.

SAMIR BHOGAYTAFreelancer and IT ConsultantCommented:
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();
      this.Page.Controls.Add(objBox);
   }

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)
      Response.Write(objBox2.Text);
0
P1ST0LPETECommented:
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.
0
Zeuss_09Author Commented:
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.

0
P1ST0LPETECommented:
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">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server" />
    <div>
        <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true" OnSelectedIndexChanged="DropDownList_SelectedIndexChanged" />
        <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
            <ContentTemplate>
                <asp:Panel ID="Panel1" runat="server" />
            </ContentTemplate>
            <Triggers>
                <asp:AsyncPostBackTrigger ControlID="DropDownList1" />
            </Triggers>
        </asp:UpdatePanel>
        <asp:Button ID="SaveButton" runat="server" Text="Save" OnClick="SaveForm" />
    </div>
    </form>
</body>
</html>

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)
            {
                CreateDynamicTable(index);
            }            
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.DropDownList_Populate();
            }
        }

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

        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";
            cell1.Controls.Add(label);

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

            TableRow row = new TableRow();
            row.Controls.Add(cell1);
            row.Controls.Add(cell2);

            Table table = new Table();
            table.Controls.Add(row);

            this.Panel1.Controls.Add(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.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Amandeep Singh BhullarCommented:
This question has been classified as abandoned and is closed as part of the Cleanup Program. See the recommendation for more details.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
ASP.NET

From novice to tech pro — start learning today.