0

我有嵌套中继器,嵌套中继器中的每个项目都有一个标签和一个按钮,我希望能够在单击按钮时访问 label.text,我想我快到了,因为我可以返回索引单击的中继器和嵌套中继器,我只是在查找标签本身时遇到了一些麻烦。

如果我不发布中继器代码,您也许可以帮助我。这是单击按钮时的代码。

Protected Sub btnEditUser_Click(ByVal sender As Object, ByVal e As System.EventArgs)

    Dim btnEditUser As Button = DirectCast(sender, Button)
    Dim reClient As RepeaterItem = DirectCast(btnEditUser.NamingContainer.Parent.Parent, RepeaterItem)
    Dim reUser As RepeaterItem = DirectCast(btnEditUser.NamingContainer, RepeaterItem)
    Dim selectedClient As Integer = reClient.ItemIndex
    Dim selectedUser As Integer = reUser.ItemIndex

    Dim UserId As Label = DirectCast(reClients.Items(selectedClient).FindControl("lUserName"), Label)

    Response.Write(selectedClient & " " & selectedUser & " " & UserId.Text)

End Sub

我目前收到此错误“对象引用未设置为对象的实例。” 当试图写入 UserId.Text 的值时,我认为我在这一行中有点错误:

Dim UserId As Label = DirectCast(reClients.Items(selectedClient).FindControl("lUserName"), Label)
4

2 回答 2

0

这只是一个猜测,但有时当并非所有行都包含您要查找的控件时,您会遇到这样的错误。通常代码会按顺序遍历行,首先遇到不包含相关控件的标题行,然后失败。

于 2011-10-14T11:38:29.937 回答
0

这是一篇很好的 MSDN 文章 - 在命名容器的层次结构中定位控件。

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

    If rootControl.ID = controlID Then
        Return rootControl
    End If

    For Each controlToSearch As Control In rootControl.Controls
        Dim controlToReturn As Control = 
            FindControlRecursive(controlToSearch, controlID)
        If controlToReturn IsNot Nothing Then
            Return controlToReturn
        End If
    Next
    Return Nothing
End Function

试试看,

Dim UserId As Label =DirectCast(FindControlRecursive(repClient,"lUserName"),Label)
于 2011-10-14T11:40:55.857 回答