2010-09-30 73 views
2

我有用5个简单的单选按钮的用户控件,我需要循环通过代码隐藏的那些,但我如何做到这一点画了一个巨大的空白。有人可以帮助请循环通过UserControl的控件

+0

您可以发布用户控件的标记以及如何定义单选按钮吗? – Oded 2010-09-30 20:24:48

回答

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

注意,这不是递归。如果你的单选按钮在控制容器的层次更深,你需要编写一个递归方法来找到它们。有关递归FindControl函数的示例,请参阅我的旧回答here

+0

你不能在用户控件中使用“this.Controls” – mattgcon 2010-09-30 23:31:32

+0

纠正,你可以“这个”但不是任何方法之外。我正在尝试设置属性(get; set;) – mattgcon 2010-09-30 23:55:21

0

这里只是猜测,但如果您尝试拥有一组相关的单选按钮,则不应该使用单独的单选按钮控件,而应该使用控件。这将保存组中的所有单选按钮,并允许您遍历它们。

+0

由于客户端的请求,我正在以此方式使用它。我更喜欢radiobuttonlist,但要求标签位于按钮之上。 – mattgcon 2010-09-30 23:31:02

+0

使用CSS将标签放在最上面。 – TheGeekYouNeed 2010-10-01 07:04:39

+0

现在我尝试使用CSS来定位它们,但我无法使它工作。 – mattgcon 2010-10-01 14:18:12

0

这可能是你的情况有点迟了,但这篇文章帮助我发现了一个解决方案,你的问题(这原来是我的确切问题) - 具体如何选择一个单选按钮组在usercontrol中如果单选按钮组更改,则不需要更改代码。这里是我想出了一个解决方案:

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 

然后,所有你需要做的是让该组中的单选按钮(并且没有其他控件):

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

很抱歉,但“使用RadioButtonList“不是修改别人编写的现有代码的好方案,因为它需要对标记和CSS进行重大更改。当然,如果我发现自己编写自己的控件,我将使用RadioButtonList。