Johnathan Elmore
Johnathan Elmore

Reputation: 2244

Adding .net RadioButtonsList control dynamically in code file, no SelectedValue in Post Back

I am having trouble getting the SelectedValue from a RadionButtonsList that I'm creating dynmically in a code file. I'm adding it to a PlaceHolder control on the aspx page. After PostBack the radio button keeps its selection on the page, but I am not able to get the value from within the code file.

I understand I can create the RadioButtonsList in the HTML page, but I need to understand how to accomplish this from only the code file. The real problem I'm having is more complicated. (Creating dynamic number of true/false RadioButtonsList controls)

quiz.aspx

<%@ Page Title="Quiz" MasterPageFile="~/MasterPage.master" Language="VB" CodeFile="quiz.aspx.vb" Inherits="quiz" %>

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">

    <asp:PlaceHolder ID="testholder" runat="server"></asp:PlaceHolder>

    <asp:Button ID="lblNext" runat="server" type="submit" Text="Next" accesskey="n"/>

</asp:Content>

MasterPage.master

<%@ Master Language="VB" CodeFile="MasterPage.master.vb" Inherits="MasterPage" %>

quiz.aspx.vp

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Dim testlist As New RadioButtonList
    testlist.Items.Add(New ListItem("test 1", "test1"))
    testlist.Items.Add(New ListItem("test 2", "test2"))
    testholder.Controls.Add(testlist)

    If (IsPostBack) Then
        Debug.WriteLine("testlist: " & testlist.SelectedValue)
    End If
End Sub

My output after submit is: "testlist: ". Any ideas?

Upvotes: 0

Views: 126

Answers (1)

Pavan
Pavan

Reputation: 4329

You have to load the controls before page_load event is triggered so that loadpostbackdata will get a chance to load the viewstate of the dynamic controls.

I am able to see the selected value after moving the dynamic controls to page_init event.

 Dim testlist As New RadioButtonList 

 Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs)
{

    testlist.Items.Add(new ListItem("test1", "test1"))
    testlist.Items.Add(new ListItem("test2", "test2"))
    testholder.Controls.Add(testlist)

} 

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
{ 

    If (IsPostBack) Then
        Debug.WriteLine(testlist.SelectedValue)
    End If

}

Upvotes: 1

Related Questions