簡體   English   中英

循環遍歷 UserControl 的控件

[英]Loop through controls of a UserControl

我有一個帶有 5 個簡單單選按鈕的用戶控件,我需要遍歷代碼隱藏中的那些,但是我在如何做到這一點上畫了一個巨大的空白。 有人可以幫忙嗎

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

請注意,這不是遞歸的。 如果您的單選按鈕在控制容器層次結構中更靠后,您將需要編寫一個遞歸方法來找到它們。 見我老的答案在這里的遞歸的FindControl函數的例子。

只是在這里猜測,但如果您嘗試使用一組相關的單選按鈕,則不應使用單個單選按鈕控件,而應使用RadioButtonList控件。 這會將所有單選按鈕保存在一個組中,並允許您對其進行迭代。

對於您的情況,這可能有點晚了,但是這篇文章幫助我找到了您的問題的解決方案(結果證明這是我的確切問題)-特別是如何以一種不會的方式在用戶控件中選擇單選按鈕組如果單選按鈕組更改,則需要更改代碼。 這是我想出的解決方案:

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。

您可以使用 Linq 遍歷所需的用戶控件,此代碼還按 TabIndex 對迭代進行排序:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM