Solved

Retreive Values From Dynamically Created Textboxes

Posted on 2011-09-08
9
409 Views
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.

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

0
Comment
Question by:Zeuss_09
9 Comments
 
LVL 4

Expert Comment

by:yesthatbob
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


0
 
LVL 10

Expert Comment

by:P1ST0LPETE
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.
0
 

Author Comment

by:Zeuss_09
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?
0
 
LVL 11

Expert Comment

by:SAMIR BHOGAYTA
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();
      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
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 10

Expert Comment

by:P1ST0LPETE
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.
0
 

Author Comment

by:Zeuss_09
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.

0
 
LVL 10

Accepted Solution

by:
P1ST0LPETE earned 500 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">
    <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
 
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.
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Just a quick little trick I learned recently.  Now that I'm using jQuery with abandon in my asp.net applications, I have grown tired of the following syntax:      (CODE) I suppose it just offends my sense of decency to put inline VBScript on a…
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…
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.

707 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

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now