mattgcon
mattgcon

Reputation: 4848

Loop through controls of a UserControl

I have a user control with 5 simple radiobuttons, I need ot loop through those in code-behind, but I am drawing a huge blank on how to do this. Can someone help please

Upvotes: 2

Views: 9146

Answers (4)

Creek Drop
Creek Drop

Reputation: 594

You can use Linq to loop through required user controls, this code also sorts iterations by TabIndex:

IEnumerable<RadioButton> rbs = this.Controls.OfType<RadioButton>().OrderBy(ci => ci.TabIndex);
foreach (RadioButton rb in rbs)
{
    // do stuff
}

Upvotes: 0

NightOwl888
NightOwl888

Reputation: 56849

This may be a little late for your case, but this post helped me to discover a solution for your question (which turned out to be my exact question) - specifically how to select a radio button group in a usercontrol in a way that doesn't require code changes if the radio button group changes. Here is the solution I came up with:

Protected Function GetRadioButtonGroup(ByVal control As Control, ByVal groupName As String) As RadioButton()
    Dim rbList As New System.Collections.Generic.List(Of RadioButton)
    If TypeOf control Is RadioButton AndAlso DirectCast(control, RadioButton).GroupName = groupName Then
        rbList.Add(control)
    End If
    If control.HasControls Then
        For Each subcontrol As Control In control.Controls
            rbList.AddRange(GetRadioButtonGroup(subcontrol, groupName))
        Next
    End If
    Return rbList.ToArray
End Function

Then all you need to do is this to get the radio buttons in the group (and no other controls):

Dim radioButtons As RadioButton() = GetRadioButtonGroup(Me, "MyGroupName")

Sorry, but "Use a RadioButtonList" is not a good solution for modifying existing code that someone else wrote, since it will require significant changes to the markup and css. Of course, if I find myself writing my own control, I will use a RadioButtonList.

Upvotes: 0

Oded
Oded

Reputation: 498904

Just guessing here, but if you are trying to have a group of related radio buttons, you shouldn't be using individual radio button controls, but a RadioButtonList control. This will hold all of the radio buttons in a group and allow you to iterate over them.

Upvotes: 0

womp
womp

Reputation: 116977

foreach (var ctl in this.Controls)
{
    if (ctl is RadioButton)
    {
       // stuff
    }
}

Note that this is not recursive. If your radiobuttons are further down in the control container heirarchy, you'll need to write a recursive method to find them. See my old answer here for an example of a recursive FindControl function.

Upvotes: 10

Related Questions