Question : VB.net how to create a hashtable with a list of all parent and child controls and values

I have an asp.net page wich contains nested Listview controls and each of those have dynamically added tables which contain dynamically added radio buttons and text boxes.  i am simply trying to store the radio button and text box ID's and Values (if checked) or Text if text box in a hashtable.  I cant seem to wrap my mind around the recursive function that would be required to do this.  I have tryied the following

Private Function RecurseControls(ByVal controls As ControlCollection) As Hashtable
        Dim htResults As New Hashtable
        Dim i As Integer = 0

        For Each ctrl As Control In controls
            'do something with control
            i = i + 1
            If TypeOf ctrl Is TextBox Then
                Dim txtBox As TextBox = ctrl
                htResults.Add(txtBox.ID.ToString, txtBox.Text)
            ElseIf TypeOf ctrl Is RadioButton Then
                Dim rButton As RadioButton = ctrl
                If rButton.Checked = True Then
                    htResults.Add(rButton.ID.ToString, rButton.Attributes("Value").ToString)
                End If
            End If
            'recurse
            If ctrl.HasControls() Then
                RecurseControls(ctrl.Controls)
            End If
        Next
        htResults.Add("Count", i)
        RecurseControls = htResults
    End Function

but I dont get anything excpet a count of 1 in my hashtable.  

Answer : VB.net how to create a hashtable with a list of all parent and child controls and values

A recursive function will declare new instances of its local variables with each iteration. You will want to pass your hashtable as a ref parameter:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
Private Sub SomeCallingFunction
    Dim ht As New Hashtable
    
    RecurseControls(Me.Controls, ht)
End Sub

Private Function RecurseControls(ByVal controls As ControlCollection, ByRef htResults As Hashtable) As Hashtable
    Dim i As Integer = 0

    For Each ctrl As Control In controls
        'do something with control
        i = i + 1
        If TypeOf ctrl Is TextBox Then
            Dim txtBox As TextBox = ctrl
            htResults.Add(txtBox.ID.ToString, txtBox.Text)
        ElseIf TypeOf ctrl Is RadioButton Then
            Dim rButton As RadioButton = ctrl
            If rButton.Checked = True Then
                htResults.Add(rButton.ID.ToString, rButton.Attributes("Value").ToString)
            End If
        End If
        'recurse
        If ctrl.HasControls() Then
            RecurseControls(ctrl.Controls, htResults)
        End If
    Next
    htResults.Add("Count", i)
    RecurseControls = htResults
End Function
Random Solutions  
 
programming4us programming4us