【问题标题】:Loop through controls of a UserControl循环通过 UserControl 的控件
【发布时间】:2011-04-19 13:43:02
【问题描述】:

我有一个带有 5 个简单单选按钮的用户控件,我需要在代码隐藏中循环遍历这些单选按钮,但我在如何做到这一点上画了一个巨大的空白。有人可以帮忙吗

【问题讨论】:

  • 您能否发布用户控件的标记以及您如何定义单选按钮?

标签: c# asp.net user-controls controls


【解决方案1】:
foreach (var ctl in this.Controls)
{
    if (ctl is RadioButton)
    {
       // stuff
    }
}

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

【讨论】:

  • 你不能在用户控件中使用“this.Controls”
  • 更正,你可以“这个”,但不能在任何方法之外。我正在尝试设置一个属性,如 (get; set;)
【解决方案2】:

只是在这里猜测,但如果您尝试使用一组相关的单选按钮,则不应使用单独的单选按钮控件,而应使用 RadioButtonList 控件。这将包含一个组中的所有单选按钮,并允许您对其进行迭代。

【讨论】:

  • 我之所以这样使用它,是因为客户的要求。我更喜欢单选按钮列表,但要求标签位于按钮顶部。
  • 使用 CSS 将标签放置在顶部。
  • 现在我尝试使用 CSS 来定位它们,但我无法让它工作。
【解决方案3】:

这对于您的情况可能有点晚了,但这篇文章帮助我找到了解决您问题的方法(结果证明这是我的确切问题) - 特别是如何以某种方式在用户控件中选择单选按钮组如果单选按钮组更改,则不需要更改代码。这是我想出的解决方案:

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。

【讨论】:

    【解决方案4】:

    您可以使用 Linq 循环访问所需的用户控件,此代码还按 TabIndex 对迭代进行排序:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-13
      • 2012-03-19
      • 1970-01-01
      • 1970-01-01
      • 2013-12-04
      相关资源
      最近更新 更多