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 开发者_StackOverflowI am drawing a huge blank on how to do this. Can someone help please
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.
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.
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.
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
}
精彩评论