asp.net loop dynamic checkboxlists' items - demo code included - cant access dynamic checkboxlistitems

seems its not easily possible to get access to the values of dynamically created controls in asp.net.
i read a bucketload of articles, but can't get anything to work
i setup a quick example with the idea of somebody perhaps seeing where im going wrong

in the code, there are 3 items in a radioboxlist
when the selectedindexchanged event is fired for the radioboxlist, then a checkboxlist is filled, and the contents is dependant on the value of the selected radioboxlist item.
e.g. you select "CARS" (radioboxlist item)
and the checkboxlist item will fill with selected cars.
the checkboxlist is a dynamic control and there can be more than one checkboxlists e.g. ferraris in one checkboxlist, porches in another checkbox list.

the crux is that i need to save which dynamically created checkboxlist items have been checked, when the selectedIndexChanged event  is fired, (and when the user then gets back to CARS, the easy part then is to re-check the items).
(access dynamically created controls)

however i cannot access the dynamically created items, at least now during the radiobuttonlist. selectindexchanged event

could someone please help me to get a list of selected checkboxlist items?


attached is a simple aspx and .vb page with all the code to show the example
 
Partial Class Default2
    Inherits System.Web.UI.Page
    Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
        If Not Page.IsPostBack Then
            'add 3 arbitrary values to radiobuttonlist
            rbl.Items.Add("Cars")
            rbl.Items.Add("Trucks")
            rbl.Items.Add("Trailers")
        End If


    End Sub

    Protected Sub rbl_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles rbl.SelectedIndexChanged
        SaveCheckBoxes()

        'create new checkboxes here for selected value
        CreateNewCheckBoxListItems()

    End Sub
    ''' <summary>
    ''' Loop through all the dynamically created checkboxlists and save the values to HiddenField1
    ''' </summary>
    ''' <remarks></remarks>
    Protected Sub SaveCheckBoxes()

        For Each FormCtrl As Control In Form.Controls
            For Each ContentControl As Control In FormCtrl.Controls
                If TypeOf ContentControl Is Panel Then
                    For Each ChildControl As Control In ContentControl.Controls
                        If TypeOf ChildControl Is CheckBoxList Then
                            For Each MyCheckBox As ListItem In CType(ChildControl, CheckBoxList).Items
                                If MyCheckBox.Selected = True Then
                                    HiddenField1.Value = HiddenField1.Value & "," & MyCheckBox.Text
                                End If
                            Next MyCheckBox
                        End If
                    Next
                End If
            Next
        Next
    End Sub
    Protected Sub CreateNewCheckBoxListItems()
        Dim iLoop As Integer = 0
        Select Case rbl.SelectedItem.Text

            Case "Cars"

                Dim NewCheckBoxList As New CheckBoxList
                NewCheckBoxList.ID = "CheckBoxListCars1"
                NewCheckBoxList.Items.Add("TestCars1")
                NewCheckBoxList.Items.Add("TestCars2")
                NewCheckBoxList.Items.Add("TestCars3")
                panel1.Controls.Add(NewCheckBoxList)

            Case "Trucks"
                For iLoop = 0 To 3
                    Dim NewCheckBoxList As New CheckBoxList
                    NewCheckBoxList.ID = "CheckBoxListTrucks" & iLoop
                    NewCheckBoxList.Style("Position") = "Absolute"
                    NewCheckBoxList.Style("Top") = "100px"
                    NewCheckBoxList.Style("left") = iLoop * 200 + 200 & "px"
                    NewCheckBoxList.Items.Add("TestTrucks" & iLoop & "A")
                    NewCheckBoxList.Items.Add("TestTrucks" & iLoop & "B")
                    NewCheckBoxList.Items.Add("TestTrucks" & iLoop & "C")
                    NewCheckBoxList.Items.Add("TestTrucks" & iLoop & "D")
                    panel1.Controls.Add(NewCheckBoxList)
                Next

                
            Case "Trailers"
                For iLoop = 0 To 3
                    Dim NewCheckBoxList As New CheckBoxList
                    NewCheckBoxList.ID = "CheckBoxListTrailers" & iLoop
                    NewCheckBoxList.Items.Add("TestTrailers" & iLoop)
                    panel1.Controls.Add(NewCheckBoxList)
                Next

        End Select
    End Sub
  
End Class





------------------------------------
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default2.aspx.vb" Inherits="Default2" %>

<!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>Untitled Page</title>
</head>
<body>

  <form runat="server" id="mainForm" method="post">
      &nbsp;<div class="exampleWrapper">
          &nbsp;
        &nbsp;&nbsp;</div>
      <table>
          <tr>
              <td style="width: 725px; height: 16px">
                  <asp:RadioButtonList ID="rbl" runat="server" AutoPostBack="True" BorderStyle="Ridge" RepeatDirection="Horizontal">
                  </asp:RadioButtonList></td>
          </tr>
      </table>
      <asp:Panel ID="panel1" runat="server" Visible="true" Height="85px" Width="728px">
                  &nbsp;&nbsp;&nbsp;
    </asp:Panel>
      &nbsp;&nbsp;
      <asp:HiddenField ID="HiddenField1" runat="server" />
  
 
      
    </form>

</body>
</html>

Open in new window

jxhardingAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Carl TawnSystems and Integration DeveloperCommented:
The problem is that because you are using dynamic controls you have to recreate them on postback in order for the page to be able to re-bind their values and allow you to read them. I've posted a modified version of your code that should allow you to do this:
    <div class="exampleWrapper"></div>
    <table>
        <tr>
            <td style="width: 725px; height: 16px">
                <asp:RadioButtonList ID="rbl" runat="server" AutoPostBack="True" BorderStyle="Ridge" RepeatDirection="Horizontal">
                </asp:RadioButtonList>
            </td>
        </tr>
    </table>
    <asp:Panel ID="panel1" runat="server" Visible="true" Height="85px" Width="728px">
    </asp:Panel>

    <asp:HiddenField ID="HiddenField1" runat="server" />
    <asp:HiddenField ID="PrevGroup" runat="server" />

Open in new window

    Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
        If Not Page.IsPostBack Then
            'add 3 arbitrary values to radiobuttonlist
            rbl.Items.Add("Cars")
            rbl.Items.Add("Trucks")
            rbl.Items.Add("Trailers")
        Else
            CreateNewCheckBoxListItems(PrevGroup.Value)
        End If

    End Sub

    Protected Sub rbl_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles rbl.SelectedIndexChanged
        SaveCheckBoxes()

        'create new checkboxes here for selected value
        CreateNewCheckBoxListItems(rbl.SelectedItem.Text)
        Me.PrevGroup.Value = rbl.SelectedItem.Text

    End Sub
    ''' <summary>
    ''' Loop through all the dynamically created checkboxlists and save the values to HiddenField1
    ''' </summary>
    ''' <remarks></remarks>
    Protected Sub SaveCheckBoxes()
        For Each FormCtrl As Control In Form.Controls
            For Each ContentControl As Control In FormCtrl.Controls
                If TypeOf ContentControl Is Panel Then
                    For Each ChildControl As Control In ContentControl.Controls
                        If TypeOf ChildControl Is CheckBoxList Then
                            For Each MyCheckBox As ListItem In CType(ChildControl, CheckBoxList).Items
                                If MyCheckBox.Selected = True Then
                                    HiddenField1.Value = HiddenField1.Value & "," & MyCheckBox.Text
                                End If
                            Next MyCheckBox
                        End If
                    Next
                End If
            Next
        Next
    End Sub

    Protected Sub CreateNewCheckBoxListItems(ByVal selected As String)
        Dim iLoop As Integer = 0
        Select Case selected

            Case "Cars"

                Dim NewCheckBoxList As New CheckBoxList
                NewCheckBoxList.ID = "CheckBoxListCars1"
                NewCheckBoxList.Items.Add("TestCars1")
                NewCheckBoxList.Items.Add("TestCars2")
                NewCheckBoxList.Items.Add("TestCars3")
                panel1.Controls.Add(NewCheckBoxList)

            Case "Trucks"
                For iLoop = 0 To 3
                    Dim NewCheckBoxList As New CheckBoxList
                    NewCheckBoxList.ID = "CheckBoxListTrucks" & iLoop
                    NewCheckBoxList.Style("Position") = "Absolute"
                    NewCheckBoxList.Style("Top") = "100px"
                    NewCheckBoxList.Style("left") = iLoop * 200 + 200 & "px"
                    NewCheckBoxList.Items.Add("TestTrucks" & iLoop & "A")
                    NewCheckBoxList.Items.Add("TestTrucks" & iLoop & "B")
                    NewCheckBoxList.Items.Add("TestTrucks" & iLoop & "C")
                    NewCheckBoxList.Items.Add("TestTrucks" & iLoop & "D")
                    panel1.Controls.Add(NewCheckBoxList)
                Next


            Case "Trailers"
                For iLoop = 0 To 3
                    Dim NewCheckBoxList As New CheckBoxList
                    NewCheckBoxList.ID = "CheckBoxListTrailers" & iLoop
                    NewCheckBoxList.Items.Add("TestTrailers" & iLoop)
                    panel1.Controls.Add(NewCheckBoxList)
                Next

        End Select
    End Sub

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
jxhardingAuthor Commented:
hi, this is great help so far thanks
i've made some progress, but i cant get any value for the text property, of the checkboxes
, it is always = ""
i think im missing something small here

for the first time i can actually get into a loop to loop controls.

i only changed the procedure SaveCheckBoxes()

the system currently loads the previous selection, as well as the current selection, and thus the screen shows 2 groups at this point in time.

(thanks for the great help so far)
Protected Sub SaveCheckBoxes()
        For Each FormCtrl As Control In Form.Controls
            For Each ContentControl As Control In FormCtrl.Controls

                For Each ChildControl As Control In ContentControl.Controls
                    If TypeOf ChildControl Is CheckBox Then
                        Dim c As CheckBox = DirectCast(ChildControl, CheckBox)
                        If c.Checked = True Then
                            HiddenField1.Value = HiddenField1.Value & "," & c.Text
                        End If

                    End If
                Next

            Next
        Next
    End Sub

Open in new window

0
jxhardingAuthor Commented:
rephrase from my side please, i can loop the items, but their checked state is always = false, even though they are checked and still visible on the screen.
0
OWASP: Avoiding Hacker Tricks

Learn to build secure applications from the mindset of the hacker and avoid being exploited.

Carl TawnSystems and Integration DeveloperCommented:
Hmm, Selected should be showing as true. You can sort the problem of it displaying multiple sets by changing the CreateNewCheckBoxListItems() method to:
    Protected Sub CreateNewCheckBoxListItems(ByVal selected As String)
        Dim iLoop As Integer = 0
        panel1.Controls.Clear()

        Select Case selected

            Case "Cars"

                Dim NewCheckBoxList As New CheckBoxList
                NewCheckBoxList.ID = "CheckBoxListCars1"
                NewCheckBoxList.Items.Add("TestCars1")
                NewCheckBoxList.Items.Add("TestCars2")
                NewCheckBoxList.Items.Add("TestCars3")
                panel1.Controls.Add(NewCheckBoxList)

            Case "Trucks"
                For iLoop = 0 To 3
                    Dim NewCheckBoxList As New CheckBoxList
                    NewCheckBoxList.ID = "CheckBoxListTrucks" & iLoop
                    NewCheckBoxList.Style("Position") = "Absolute"
                    NewCheckBoxList.Style("Top") = "100px"
                    NewCheckBoxList.Style("left") = iLoop * 200 + 200 & "px"
                    NewCheckBoxList.Items.Add("TestTrucks" & iLoop & "A")
                    NewCheckBoxList.Items.Add("TestTrucks" & iLoop & "B")
                    NewCheckBoxList.Items.Add("TestTrucks" & iLoop & "C")
                    NewCheckBoxList.Items.Add("TestTrucks" & iLoop & "D")
                    panel1.Controls.Add(NewCheckBoxList)
                Next


            Case "Trailers"
                For iLoop = 0 To 3
                    Dim NewCheckBoxList As New CheckBoxList
                    NewCheckBoxList.ID = "CheckBoxListTrailers" & iLoop
                    NewCheckBoxList.Items.Add("TestTrailers" & iLoop)
                    panel1.Controls.Add(NewCheckBoxList)
                Next

        End Select
    End Sub

Open in new window

0
jxhardingAuthor Commented:
oh my word , im on the brink of saying i love you!!

thanks a million!

thanks so much!!
0
jxhardingAuthor Commented:
This is just one of those life-saving help calls from a great expert. thanks a million!
there is no proper working example on the net of a .net dynamic control test form with checkboxlists, this will hopefully help other people
0
Carl TawnSystems and Integration DeveloperCommented:
Awww, shucks :)
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
ASP.NET

From novice to tech pro — start learning today.