Search code examples
asp.netvb.netradiobuttonlist

Dynamically adding entries on RadioButtonList/ RadioButtonList not visible


I am trying to add entries on a RadioButtonList dynamically (not from a database). So far I have the following code [markup and .vb] but the ListItems that are added dynamically are not shown on the screen.

When I added some ListItems at markup they showed correctly but I want to add them in a completely dynamic way as I cannot know how many entries will be needed prior to execution.

Markup:

    <asp:RadioButtonList ID="RadList" runat="server" Height="42px" Width="268px">
        <asp:ListItem Text="" />
    </asp:RadioButtonList>

VB code:

    RadList = New RadioButtonList()
If (Not IsPostBack) Then
    Dim bullet As String
    Dim i As Integer = 0
    For Each bullet In question.answers
        Dim item As ListItem
        item = New ListItem("" & bullet)

        RadList.Items.Add(item)
        MsgBox("Added.." & RadList.Items(i).Text)
        i = i + 1
    Next
End If
RadList.ForeColor = Drawing.Color.Black
RadList.Visible = True

I am interested as to why the entries that are added in a dynamic way are not shown on the screen.


Solution

  • All you have to do is to remove the RadList = New RadioButtonList() in your code because it is creating a new object named RadList of the RadioButtonList and ignoring your control. The code is below.

        If (Not IsPostBack) Then
            Dim bullet As String
            Dim i As Integer = 0
            For Each bullet In question.answers()
                Dim item As ListItem
                item = New ListItem("" & bullet)
    
                RadList.Items.Add(item)
                MsgBox("Added.." & RadList.Items(i).Text)
                i = i + 1
            Next
        End If
        RadList.ForeColor = Drawing.Color.Black
        RadList.Visible = True