<html> <head id="Head1" runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <asp:Panel ID="container" runat="server"> </asp:Panel> <div> <asp:Button ID="btnload" runat="server" Text="Load" /> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> no of loops</div> <asp:Button ID="btnselected" runat="server" Text="selected" /> <asp:TextBox ID="TextBox2" runat="server" style="margin-top: 26px"></asp:TextBox> </form> </body> </html>
Protected Sub getradioId_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnload.Click Dim tbl As New Table tbl.Width = 500 Dim i As Integer = 0 Do Until i = TextBox1.Text Dim tblrow As New TableRow tblrow.Width = 80% Dim tblcellrad As New TableCell tblcellrad.Width = 100 Dim tblcellname As New TableCell tblcellname.Width = 300 Dim cand As New TextBox cand.ID = i i += 1 Dim rad As New RadioButton 'generate controls (radiobuttons and textbox) rad.GroupName = "one" rad.ID = i rad.Text = "rad" & i cand.Text = "candidate " & i.ToString If i Mod 2 = 1 Then 'set row colour tblrow.Style.Add("background-color", "#EEEEEE") Else tblrow.Style.Add("background-color", "#E0E0E0") End If tblcellrad.Controls.Add(rad) 'add controls to cells tblcellname.Controls.Add(cand) tblrow.Controls.Add(tblcellname) 'add cells to rows tblrow.Controls.Add(tblcellrad) tbl.Controls.Add(tblrow) 'add row to table container.Controls.Add(tbl) Loop End Sub Protected Sub btnselected_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnselected.Click Dim radios = Controls.OfType(Of RadioButton).AsQueryable() For Each r As RadioButton In radios If r.Checked Then TextBox2.Text = r.ID.ToString End If Next End Sub
Quote:When dynamically adding controls to an ASP.NET page in runtime the object references are lost at postback because they have no handle in the codebehind. The values entered by the user is not availible when accessing these objects after postback, and they seem empty. This article describes how to use ViewState to recreate and reinsert the postback values into the objects to access their values.
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)