Suren
Suren

Reputation: 7

Loop through UpdatePanel Controls

How can I loop through Controls within an Update panel in asp.net? I am using VS 2010 with vb.net and having an update panel in my page in that have placed 10 check boxes, I need to get the Checkbox ID s in the foreach loop.

For Each ChkBox In UpdatePanel1.ContentTemplateContainer.Controls.OfType(Of CheckBox)()
      If ChkBox.Checked = True Then 
           Session("TaskName") = ChkBox.Text 
                     Else 
      End If
Next

Upvotes: 0

Views: 1215

Answers (2)

Rob Leigh
Rob Leigh

Reputation: 1

Update panels have a internal ContentTemplate which holds the controls you're looking for.

Recursively, you can do this for the answer offered by Karl Anderson, called once for the ContentTemplate and then subsequently for the Checkbox controls using the previous output; although I've not tested this method.

However, the below code works literally for your question:

'get internal ContentTemplate for the parent update panel
For Each contenttemplate As Control In upnlStages.Controls

    For Each checkbox As CheckBox In contenttemplate.Controls.OfType(Of CheckBox)()
        'do whatever you want with the individual contro
        if checkbox.checked and instr(checkbox.ID, "chkQuestion1") = 1 then
            'do stuff
        end if

    Next

Next

Upvotes: 0

Karl Anderson
Karl Anderson

Reputation: 34846

The following will recursively search the root control you specify, looking for the type of control you tell it to:

Public Shared Sub FindControlsRecursive(root As Control, type As Type, ByRef list As List(Of Control))
    If root.Controls.Count <> 0 Then
        For Each theControl As Control In root.Controls
            If theControl.GetType() = type Then
                list.Add(theControl)
            ElseIf theControl.HasControls Then
                FindControlsRecursive(theControl, type, list)
            End If
        Next
    End If
End Sub

Usage:

Dim checkboxes As New List(Of CheckBox)
FindControlRecursive(UpdatePanel1, GetType(CheckBox), checkboxes)

Now you can loop through each checkbox, like this:

Dim checkboxIds As New List(Of Integer) 
For Each theCheckBox As CheckBox In checkboxes
    ' Grab ID here
    checkboxIds.Add(Convert.ToInt32(theCheckBox.ID))
Next

Upvotes: 1

Related Questions