Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1289
  • Last Modified:

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

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
a222493
Asked:
a222493
1 Solution
 
viola123Commented:
this is no doubt an easy question, but i would like to see your code first

cheers
viola
0
 
boulder_bumCommented:
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
 
raed_hasanCommented:
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
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.

 
PichtoCommented:
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
 
a222493Author Commented:
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
 
boulder_bumCommented:
You had it right.

Something like:

string var = ((TextBox) myTable.Rows[0].Cells[0].Controls[0] ).Text;
0
 
a222493Author Commented:
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
 
boulder_bumCommented:
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

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.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now