我有嵌套的转发器,嵌套转发器中的每个项目都有一个标签和一个按钮,我希望能够在点击按钮时访问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)
答案 0 :(得分:0)
这只是猜测,但有时当你并非所有行都包含你正在寻找的控件时,你会得到这样的错误。通常,代码按顺序循环遍历行,首先命中不包含相关控件的标题行,然后失败。
答案 1 :(得分:0)
这是一篇很好的MSDN文章 - 在名称containers的层次结构中查找控件。
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)