Solved

How to access the value of a textbox in a dynamically created HtmlTable

Posted on 2004-10-04
8
1,279 Views
Last Modified: 2012-05-05
Hi,

This is probably pretty simple but...

I am dynamically adding rows to a HtmlTable that contain Textbox controls. (There may be more than one server control/textbox in a given cell)

How do I get the value of a textbox when the form is posted back?

I would expect something like:

TextBox t = (TextBox)Table1.Rows[0].Cells[0].Controls[0];
String s = t.Text;

(I may be using the controls colletion incorrectly...)

Or at least that is the kind of solution I'm looking for...
0
Comment
Question by:a222493
8 Comments
 
LVL 6

Expert Comment

by:viola123
ID: 12223840
this is no doubt an easy question, but i would like to see your code first

cheers
viola
0
 
LVL 8

Expert Comment

by:boulder_bum
ID: 12224378
Oddly enough, you have to rebuild each of the controls (just as you did when you built them the first time) before you are able to access their values.

The reason is that the page unloads every control after a web response is delivered to the client. It doesn't remember that there were controls there to begin with, thus it doesn't know how to associate anything with the ViewState delivered back to the server. Once you (re)create the controls, the page plays catch-up loading ViewState and stuff. You can then access them like you'd access any design-time created control.
0
 
LVL 2

Expert Comment

by:raed_hasan
ID: 12224393
Hi,

Table cann't persist its status between postback. So you have to create it
every time and add controls as well.

Or you can use request.form("yourtextboxid") to get textbox value directly.
But you still need to create table to display on the page.

and you can do more than this but really from my part of view this is not simply at all.
you can make an custom control derived from textbox which implement IPostBackDataHandler
and on
public bool LoadPostData(string postDataKey, System.Collections.Specialized.NameValueCollection postCollection)
save somewhere in session your data. Session["key"] =
postCollection[postDataKey].ToString();
You cand override prerender on control to put your data back. this.Text =
Session["key"].ToString();
I think you better make a class to do this stuff for saving and getting you
data from session for all your dynamical controls.
So, this is very simple.  :)

Regards
0
 
LVL 4

Expert Comment

by:Pichto
ID: 12225400
Hi,

I can give you one my old test on that subject :

<%@ Page Language="C#" ContentType="text/html" ResponseEncoding="iso-8859-1" %>
<%@ import Namespace="System" %>
<%@ import Namespace="System.Web" %>
<%@ import Namespace="System.Web.UI.WebControls" %>
<script runat="server">
    void Page_Load(object sender, EventArgs e)
    {
        // Generate rows and cells
        int numrows = 4;
        int numcols = 6;
        int i;
        bool firstrow = true;
   
        for (int j=0; j<numrows; j++) {
   
            TableRow r = new TableRow();
   
            switch (j)
            {
                case 0:
                    for (i=0; i<numcols; i++)
                    {
                        TableCell c = new TableCell();
                        if (i==0)
                        {
                            c.RowSpan = 4;
                        }
                        c.HorizontalAlign = HorizontalAlign.Center;
                        c.VerticalAlign = VerticalAlign.Middle;
                        TextBox tbTemp = new TextBox();
                        tbTemp.ID = "textbox" + j.ToString() + i.ToString();
                        tbTemp.Text = "test test. Box #" + j.ToString() + i.ToString();
                        c.Controls.Add(tbTemp);
                        r.Cells.Add(c);
                    }
                    break;
   
                case 1:
                    for (i=1; i<numcols; i++)
                    {
                        TableCell c = new TableCell();
                        c.HorizontalAlign = HorizontalAlign.Center;
                        c.VerticalAlign = VerticalAlign.Middle;
                        TextBox tbTemp = new TextBox();
                        tbTemp.ID = "textbox" + j.ToString() + i.ToString();
                        tbTemp.Text = "test test. Box #" + j.ToString() + i.ToString();
                        c.Controls.Add(tbTemp);
                        r.Cells.Add(c);
                    }
                    break;
   
                case 2:
                    for (i=1; i<numcols; i++)
                    {
                        if(i<numcols-1)
                        {
                            TableCell c = new TableCell();
                            c.HorizontalAlign = HorizontalAlign.Center;
                            c.VerticalAlign = VerticalAlign.Middle;
                            TextBox tbTemp = new TextBox();
                            tbTemp.ID = "textbox" + j.ToString() + i.ToString();
                            tbTemp.Text = "test test. Box #" + j.ToString() + i.ToString();
                            c.Controls.Add(tbTemp);
                            r.Cells.Add(c);
                        }
                        else
                        {
                            TableCell c = new TableCell();
                            c.RowSpan = 2;
                            c.HorizontalAlign = HorizontalAlign.Center;
                            c.VerticalAlign = VerticalAlign.Middle;
                            r.Cells.Add(c);
                        }
                    }
                    break;
   
                case 3:
                    for (i=2; i<numcols-1; i++)
                    {
                        if (i==2)
                        {
                            TableCell c = new TableCell();
                            c.ColumnSpan = 2;
                            c.HorizontalAlign = HorizontalAlign.Center;
                            c.VerticalAlign = VerticalAlign.Middle;
                            r.Cells.Add(c);
                        }
                        else
                        {
   
                            TableCell c = new TableCell();
                            c.HorizontalAlign = HorizontalAlign.Center;
                            c.VerticalAlign = VerticalAlign.Middle;
                            TextBox tbTemp = new TextBox();
                            tbTemp.ID = "textbox" + j.ToString() + i.ToString();
                            tbTemp.Text = "test test. Box #" + j.ToString() + i.ToString();
                            c.Controls.Add(tbTemp);
                            r.Cells.Add(c);
                        }
                    }
                    break;
            }
        Table1.Rows.Add(r);
        }
    }
   
   
    void Button1_OnClick(object sender, EventArgs e) {
        string strTemp = ((TextBox)FindControl("textbox00")).Text;
        //TextBox myControl1 = (TextBox)FindControl("textbox00");
        //string strTemp = myControl1.Text;
        Response.Write(strTemp);
    }

</script>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
</head>
<body>
    <h3><font face="Verdana">Table Example</font>
    </h3>
    <form runat="server">
        <asp:Table id="Table1" runat="server" BorderWidth="1px" BorderColor="IndianRed" CellSpacing="0" CellPadding="2" Font-Size="8pt" Font-Name="Verdana" BorderStyle="Dotted" HorizontalAlign="Center" Width="100%" GridLines="Both" ForeColor="Blue"></asp:Table>
        <p>
            <asp:button id="Button1" onclick="Button1_OnClick" runat="server" Text="PostBack"></asp:button>
        </p>
    </form>
</body>
</html>

HTH

Pichto
0
6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

 

Author Comment

by:a222493
ID: 12227793
Thanks for the responses, but they don't exactly address the question.  I'm aware of the need to "re-create" the controls on each postback, but that's not what I'm interested in here.  Let's assume that there will only be one round trip, and the controls in the table have been created with the designer.  However, I don't want to reference the objects by name.  I'd like to use the name of the table as my starting point.  My question has more to do with the Object structure.  The closest response that would help is in pichto's post.  The "FindControl" method would work, but I'm interested in how to access the control directly by referencing its position.

Here is my code:
------------------------------------------------------------------------------
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace DynamicTableTest
{
      /// <summary>
      /// Summary description for WebForm1.
      /// </summary>
      public class WebForm1 : System.Web.UI.Page
      {
            protected System.Web.UI.HtmlControls.HtmlTable Table1;
            protected System.Web.UI.WebControls.TextBox TextBox2;
            protected System.Web.UI.WebControls.TextBox TextBox3;
            protected System.Web.UI.WebControls.TextBox TextBox4;
            protected System.Web.UI.WebControls.Button Button1;
            protected System.Web.UI.WebControls.TextBox TextBox5;
            protected System.Web.UI.WebControls.TextBox TextBox1;
      
            private void Page_Load(object sender, System.EventArgs e)
            {

                  // Put user code to initialize the page here


            }

            #region Web Form Designer generated code
            override protected void OnInit(EventArgs e)
            {
                  //
                  // CODEGEN: This call is required by the ASP.NET Web Form Designer.
                  //
                  InitializeComponent();
                  base.OnInit(e);
            }
            
            /// <summary>
            /// Required method for Designer support - do not modify
            /// the contents of this method with the code editor.
            /// </summary>
            private void InitializeComponent()
            {    
                  this.Button1.Click += new System.EventHandler(this.Button1_Click);
                  this.Load += new System.EventHandler(this.Page_Load);

            }
            #endregion

            private void Button1_Click(object sender, System.EventArgs e)
            {
                  TextBox t = (TextBox)Table1.Rows[0].Cells[0].Controls[0];
                  String s = t.Text;
                  String s1 = t.Text;

            }
      }
}

<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="DynamicTableTest.WebForm1" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
      <HEAD>
            <title>WebForm1</title>
            <meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
            <meta name="CODE_LANGUAGE" Content="C#">
            <meta name="vs_defaultClientScript" content="JavaScript">
            <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
      </HEAD>
      <body MS_POSITIONING="GridLayout">
            <form id="Form1" method="post" runat="server">
                  <TABLE id="Table1" style="Z-INDEX: 101; LEFT: 208px; WIDTH: 320px; POSITION: absolute; TOP: 56px; HEIGHT: 168px"
                        cellSpacing="1" cellPadding="1" width="300" border="1" runat="server">
                        <TR>
                              <TD>
                                    <asp:TextBox id="TextBox2" runat="server"></asp:TextBox>
                                    <asp:TextBox id="TextBox5" runat="server"></asp:TextBox></TD>
                              <TD>
                                    <asp:TextBox id="TextBox1" runat="server"></asp:TextBox></TD>
                        </TR>
                        <TR>
                              <TD>
                                    <asp:TextBox id="TextBox3" runat="server"></asp:TextBox></TD>
                              <TD>
                                    <asp:TextBox id="TextBox4" runat="server"></asp:TextBox></TD>
                        </TR>
                  </TABLE>
                  <asp:Button id="Button1" style="Z-INDEX: 102; LEFT: 272px; POSITION: absolute; TOP: 256px" runat="server"
                        Text="Button"></asp:Button>
            </form>
      </body>
</HTML>


0
 
LVL 8

Expert Comment

by:boulder_bum
ID: 12228294
You had it right.

Something like:

string var = ((TextBox) myTable.Rows[0].Cells[0].Controls[0] ).Text;
0
 

Author Comment

by:a222493
ID: 12228518
The thing I'm curious about is the .Controls[??]

If I store two controls in one cell, I would expect to reference them Controls[0] & Controls[1] repectively.  However, I can only reference the first control I add, and get an error when referencing Controls[0] or Controls[2].  

Any Ideas?
0
 
LVL 8

Accepted Solution

by:
boulder_bum earned 250 total points
ID: 12229001
Often ASP.NET will insert a Literal control between the ones you add, so you may have to reference .Controls[1] and .Controls[3] or something. I usually just place a breakpoint at the point I first reference the controls and check the collection's structure in the watch window of the debugger.
0

Featured Post

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

In this Article, I will provide a few tips in problem and solution manner. Opening an ASPX page in Visual studio 2003 is very slow. To make it fast, please do follow below steps:   Open the Solution/Project. Right click the ASPX file to b…
Today is the age of broadband.  More and more people are going this route determined to experience the web and it’s multitude of services as quickly and painlessly as possible. Coupled with the move to broadband, people are experiencing the web via …
It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
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…

757 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