getting data from dynamically added controls

akak

New member
Joined
Aug 3, 2006
Messages
2
Programming Experience
Beginner
Hello~
I have a question on getting data back from the controls generated during runtime.

The following code are which I have tried. when user click the button "enter Details", It will generate sets of controls for data entering. However, it could only show the interface of the newly generated controls, when I try to get back the user entered value from them after user clicked buttom "summit", the controls seems disappeared. So can not get back the values. :confused:

what's wrong with the code??

Also, is there any ways to build event handler for those generated buttons(p.s maybe many-many buttons, e.g the "test" button)

test.aspx.vb
VB.NET:
Partial Class test
  Inherits System.Web.UI.Page
  Dim var As Integer = 0

  Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
  End Sub

  Protected Sub btnEnter_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnEnter.Click
    Me.PlInput.Visible = True
    Me.btnSummit.Visible = True

    Dim i As Integer

    ' get the value entered
    var = Integer.Parse(Me.ddlChild.SelectedValue())

    ' inside PlInput, build the following things for input
    For i = 1 To var
      ' build label
      Dim t1 As New Label
      t1.ID = "lbchild" + i.ToString
      t1.Height = 1
      t1.Text = "Child " + i.ToString + " : "
      t1.Width = 64
      Me.PlInput.Controls.Add(t1)
      Me.PlInput.Controls.Add(New LiteralControl("<br>Name: "))

      ' build textbox
      Dim t2 As New TextBox
      t2.ID = "tbName" + i.ToString
      Me.PlInput.Controls.Add(t2)
      Me.PlInput.Controls.Add(New LiteralControl(" with "))

      ' build dropdownlist
      Dim t3 As New DropDownList
      t3.ID = "ddlVarNo" + i.ToString
      t3.Width = 48
      Dim t3_1 As New ListItem
      t3_1.Selected = True
      t3_1.Text = 1
      t3_1.Value = 1
      t3.Items.Add(t3_1)
      Dim t3_2 As New ListItem
      t3_2.Selected = False
      t3_2.Text = 2
      t3_2.Value = 2
      t3.Items.Add(t3_2)
      Dim t3_3 As New ListItem
      t3_3.Selected = False
      t3_3.Text = 3
      t3_3.Value = 3
      t3.Items.Add(t3_3)
      Dim t3_4 As New ListItem
      t3_4.Selected = False
      t3_4.Text = 4
      t3_4.Value = 4
      t3.Items.Add(t3_4)
      Me.PlInput.Controls.Add(t3)
      Me.PlInput.Controls.Add(New LiteralControl(" variable(s)<br>"))

      ' build button
      Dim t4 As New Button
      t4.ID = "btntest" + i.ToString
      t4.Text = "test"
      Me.PlInput.Controls.Add(t4)
      Me.PlInput.Controls.Add(New LiteralControl("<br>"))
      Me.PlInput.Controls.Add(New LiteralControl("<br>"))

    Next
  End Sub

  Protected Sub btnSummit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSummit.Click
    Me.PlOutput.Visible = True
    Dim i As Integer
    Dim name As String
    Dim tb As TextBox
    Dim ddl As DropDownList
    Dim varNo As Integer

    ' report the input data
    For i = 1 To var
      tb = Me.PlInput.FindControl("tbName" + i.ToString)
      name = tb.Text
      ddl = Me.PlInput.FindControl("ddlVarNo" + i.ToString)
      varNo = Integer.Parse(ddl.SelectedValue)

      Me.PlInput.Controls.Add(New LiteralControl(name + " has " + varNo + " variable(s)" + "<br>"))
    Next
  End Sub

End Class
the web form
HTML:
<html>
  <head runat="server">
    <title>Untitled Page</title>
  </head>
  <body>
    <form id="form1" runat="server">
      <div>
        with 
        <asp:DropDownList ID="ddlChild" runat="server">
          <asp:ListItem Value="1"></asp:ListItem>
          <asp:ListItem>2</asp:ListItem>
          <asp:ListItem>3</asp:ListItem>
          <asp:ListItem>4</asp:ListItem>
          <asp:ListItem>5</asp:ListItem>
        </asp:DropDownList>
        child
        <asp:Button ID="btnEnter" runat="server" Text="Enter details" />
        <asp:Panel ID="PlInput" runat="server" Height="136px" Width="560px" Visible="False">
        </asp:Panel>
      </div>
      <asp:Panel ID="PlOutput" runat="server" Height="136px" Width="560px" Visible="False">
      </asp:Panel>
      <asp:Button ID="btnSummit" runat="server" Text="Summit" Visible="False" />
    </form>
  </body>
</html>
 
Last edited by a moderator:
two things:

1) this is the VB.NET area of the vbdotnet.com forums - you should post asp questions in the ASP.NET area of the forums. it is likely that a moderator will move this post, but in future you should post in the relevant section

2) when you post code, type the word
VB.NET:
[/B] then paste your code, then type [B][/co[/B][B]de][/B]. if, when you paste your code, it appears all in colours and slammed against the left edge of the box, look for the button in the top right of the post screen that looks like this: A/[B][U][I]A[/I][/U][/B]
its the plain/advanced switcher button.. when in advanced mode the box works a bit like MS word in terms of formatting, but it ruins code indentation and makes a major mess
 
Retaining State for Dynamically Created Controls

I've moved this thread to the ASP.NET category.
Please follow the link in my signature to see how the code tags are used.

akak said:
the controls seems disappeared. So can not get back the values.
When a page is posted back to the server as a result of user interaction, a new instance of the codebehind class is instantiated, and all the variables of the class are set with values from the ViewState. The objects we access from the codebehind page seem like the same controls, but they are actually new controls whose values come from the ViewState and ASP.NET state management. The controls are able to get these values if the control names are the same, and this is the secret.
First you create a protected property that uses the viewstate to remember the number of controls created. Then on page load you check to see if the load was caused by a postback. If so you need to create the controls again using the same names as before. Note that I have changed your variable named var to the more appropriately named variable NumberOfControls.
VB.NET:
Option Strict On

Partial Class test
    Inherits System.Web.UI.Page

    Protected Property NumberOfControls() As Integer
        Get
            Return CInt(ViewState("NumberOfControls"))
        End Get
        Set(ByVal value As Integer)
            ViewState("NumberOfControls") = value
        End Set
    End Property

    Protected Sub Page_Load(ByVal sender As Object, _
      ByVal e As System.EventArgs) Handles Me.Load
        If Page.IsPostBack Then
            CreateControls()
        Else
            NumberOfControls = 0
        End If
    End Sub

    Protected Sub btnEnter_Click(ByVal sender As Object, _
      ByVal e As System.EventArgs) Handles btnEnter.Click
        Me.plInput.Visible = True
        Me.btnSummit.Visible = True

        ' get the value entered
        NumberOfControls = Integer.Parse(Me.ddlChild.SelectedValue())
        CreateControls()
    End Sub

    Private Sub CreateControls()
        ' inside PlInput, build the following things for input
        plInput.Controls.Clear()
        Me.plInput.Controls.Add(New LiteralControl("<br />"))
        For i As Integer = 1 To NumberOfControls
            ' build label
            Dim t1 As New Label
            t1.ID = "lbchild" & i.ToString
            t1.Text = "Child " & i.ToString + " : "
            Me.plInput.Controls.Add(t1)
            Me.plInput.Controls.Add(New LiteralControl("<br />Name: "))

            ' build textbox
            Dim t2 As New TextBox
            t2.ID = "tbName" & i.ToString
            Me.plInput.Controls.Add(t2)
            Me.plInput.Controls.Add(New LiteralControl(" with "))

            ' build dropdownlist
            Dim t3 As New DropDownList
            t3.ID = "ddlVarNo" & i.ToString
            t3.Width = 48
            For j As Integer = 1 To 20
                Dim li As New ListItem
                li.Text = j.ToString
                li.Value = j.ToString
                t3.Items.Add(li)
            Next j
            Me.plInput.Controls.Add(t3)
            Me.plInput.Controls.Add(New LiteralControl(" variable(s)<br />"))

            ' build button
            Dim t4 As New Button
            t4.ID = "btntest" & i.ToString
            t4.Text = "test"
            Me.plInput.Controls.Add(t4)
            Me.plInput.Controls.Add(New LiteralControl("<br />"))
            Me.plInput.Controls.Add(New LiteralControl("<br />"))
        Next i
    End Sub

    Protected Sub btnSummit_Click(ByVal sender As Object, _
      ByVal e As System.EventArgs) Handles btnSummit.Click
        Me.plOutput.Visible = True
        Dim i As Integer
        Dim name As String
        Dim tb As TextBox
        Dim ddl As DropDownList
        Dim varNo As Integer

        ' report the input data
        For i = 1 To NumberOfControls
            tb = CType(Me.plInput.FindControl("tbName" & i.ToString), TextBox)
            name = tb.Text
            ddl = CType(Me.plInput.FindControl("ddlVarNo" & i.ToString), DropDownList)
            varNo = Integer.Parse(ddl.SelectedValue)

            Me.plInput.Controls.Add(New LiteralControl( _
              name & " has " & varNo & " variable(s)" & "<br />"))
        Next
    End Sub

End Class
The aspx page:
HTML:
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="test.aspx.vb" Inherits="test" %>

<!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>Retaining State for Dynamically Created Controls</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            with 
            <asp:DropDownList ID="ddlChild" runat="server">
                <asp:ListItem Value="1" />
                <asp:ListItem Value="2" />
                <asp:ListItem Value="3" />
                <asp:ListItem Value="4" />
                <asp:ListItem Value="5" />
            </asp:DropDownList>
            child
            <asp:Button ID="btnEnter" runat="server" Text="Enter details" />
            <asp:Panel ID="plInput" runat="server" Visible="false" />
        </div>
        <asp:Panel ID="plOutput" runat="server" Visible="false" />
        <asp:Button ID="btnSummit" runat="server" Text="Summit" Visible="False" />
    </form>
</body>
</html>
Hope this helps and welcome to the forum. ;)
 
Last edited:
Back
Top