FindControl in gridview on web page which is on master page.

FindControl will not work when searching for control in gridview which in on master page.  Neither one of the 'Dim ....' options listed below will work.  This is on a master page, but it is in the RowDataBound routine where I am trying to access the control.

Protected Sub SchLayer1GridView_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)

Dim NewNameDrpDn As DropDownList = CType(e.Row.FindControl("DrpDnName1"), DropDownList)

Dim NewNameDrpDn As DropDownList = DirectCast(e.Row.FindControl("DrpDnName1"), DropDownList)

End Sub

Any help would be appreciated.

Thanks,
rckrchAsked:
Who is Participating?
 
Chinmay PatelConnect With a Mentor Enterprise ArchitectCommented:
FindControl only works if the child control is directly container within a container. In your case there is a hierarchy of containers. This classic problem is solved with the following snippet.

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

Open in new window


Source MSDN Link: https://msdn.microsoft.com/en-us/library/y81z8326.aspx?cs-save-lang=1&cs-lang=vb#code-snippet-1
1
 
Chinmay PatelEnterprise ArchitectCommented:
Requesting a close as Author has endorsed the comment and technically this is the correct answer.
I am more than happy to explain further or correct my answer if author / moderator objects.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.