以编程方式访问webcontrols(通过FindControl)

时间:2014-07-18 08:36:14

标签: asp.net vb.net

我对.net相对较新,我正在尝试根据下拉框的值启用/禁用文本框。 (用户选择5个位置,只显示5个(10井,2个5个)框。)

通过阅读此处和本地其他地方的主题,我认为FindControl是可行的方法(在页面上找到控件然后根据需要显示或不显示),但是下面的代码在txtBox上生成NullReferenceException.Visible =是的,因为,txtBox是“没什么”。

        Dim txtBox As TextBox = New TextBox()
        Dim textboxName As String

...

        For LoopCounter = 1 To 10
            If LoopCounter < ddNumberOfPlaces.SelectedValue + 1 Then
                textboxName = "txtGuestName" + CStr(LoopCounter)
                txtBox = CType(FindControl(textboxName), TextBox)
                txtBox.Visible = True
                txtBox = CType(FindControl("txtGuestOrganisation" + CStr(LoopCounter)), TextBox)
                txtBox.Visible = True
            Else
                txtBox = CType(FindControl("txtGuestName" + CStr(LoopCounter)), TextBox)
                txtBox.Visible = False
                txtBox = CType(FindControl("txtGuestOrganisation" + CStr(LoopCounter)), TextBox)
                txtBox.Visible = False
            End If
        Next

那我做错了什么?这是实现这个的最好方法吗?

先谢谢。

P.S。 textboxName(在异常点)包含有效的控件ID。

1 个答案:

答案 0 :(得分:1)

如果您使用母版页,则FindControl不起作用。 FindControl仅返回顶级控件。它没有递归地找到控件。您可以使用以下函数递归查找控件。不要调用FindControl,而是调用此函数。

     Private Function FindControlRecursive(ByVal rootControl As Control, ByVal controlID As String) As Control
        If (rootControl.ID = controlID) Then
            FindControlRecursive = rootControl
        Else
            For Each controlToSearch As Control In rootControl.Controls

                Dim controlToReturn As Control = FindControlRecursive(controlToSearch, controlID)
                If (controlToReturn IsNot Nothing) Then
                    FindControlRecursive = controlToReturn
                End If

            Next
            FindControlRecursive = Nothing
        End If
    End Function

感谢。你的功能似乎总是返回“Nothing”所以我稍微修改了它。

Private Function FindControlRecursive(ByVal rootControl As Control, ByVal controlID As String) As Control

    Dim controlToReturn As Control = Nothing

    If (rootControl.ID = controlID) Then
        controlToReturn = rootControl
    Else
        For Each controlToSearch As Control In rootControl.Controls
            If (controlToReturn Is Nothing) Then
                controlToReturn = FindControlRecursive(controlToSearch, controlID)
            End If
        Next
    End If
    FindControlRecursive = controlToReturn
End Function