get value of label when button clicked in nested repeater asp.net vb

2.3k Views Asked by At

I have nested repeaters, each item in the nested repeater has a label and a button on it, i want to beable to access the label.text when the button is clicked, I think i'm nearly there as I can return the index of the repeater and nested repeater that is clicked, i'm just having some trouble finding the label itself.

You might be able to help me without me posting the repeater code. Here is my code behind for when the button is clicked.

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

I'm currently getting this error 'Object reference not set to an instance of an object.' when trying to write the value of UserId.Text so i think i've got it slightly wrong in this line:

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

There are 2 best solutions below

0
On

This is just a guess, but sometimes you get errors like this when not all rows contain the control you're looking for. Often the code loops through the rows in order, hits a header row first that doesn't contain the relevant control, and fails.

0
On

Here is a good MSDN article - Locating a Control Inside a Hierarchy of Naming 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

Try it,

Dim UserId As Label =DirectCast(FindControlRecursive(repClient,"lUserName"),Label)