R – Find controls on sharepoint master page

asp.netmaster-pagessharepoint

I'm trying to loop through all the controls on a sharepoint page, for the purposes of testing i just want to output the control ID

this is the code i'm using

Public Shared Sub SubstituteValues3(ByVal CurrentPage As Page, ByRef s As StringBuilder)

    'Page()
    '- MasterPage
    '- HtmlForm
    '- ContentPlaceHolder
    '- The TextBoxes, etc.

    For Each ctlMaster As Control In CurrentPage.Controls


        If TypeOf ctlMaster Is MasterPage Then
            HttpContext.Current.Response.Output.Write("Master Page <br/>")

            For Each ctlForm As Control In ctlMaster.Controls

                If TypeOf ctlForm Is HtmlForm Then
                    HttpContext.Current.Response.Output.Write("HTML Form <br/>")

                    For Each ctlContent As Control In ctlForm.Controls
                        If TypeOf ctlContent Is ContentPlaceHolder Then
                            HttpContext.Current.Response.Output.Write("Content Placeholder <br/>")

                            For Each ctlChild As Control In ctlContent.Controls
                                HttpContext.Current.Response.Output.Write(ctlChild.ID.ToString & "<br />")
                            Next
                        End If
                    Next
                End If
            Next
        End If
    Next

    HttpContext.Current.Response.Output.Write("--------------")
    HttpContext.Current.Response.End()

however it's not getting past the 'MasterPage' output.

I would expect to see the names of all the controls i have inside my content placeholder but i find it all a bit confusing.

Best Answer

Start with Page.Master.Controls

From there what you have should basically work

        For Each ctlForm As Control In Page.Master.Controls

            If TypeOf ctlForm Is HtmlForm Then
                HttpContext.Current.Response.Output.Write("HTML Form <br/>")

                For Each ctlContent As Control In ctlForm.Controls
                    If TypeOf ctlContent Is ContentPlaceHolder Then
                        HttpContext.Current.Response.Output.Write("Content Placeholder <br/>")

                        For Each ctlChild As Control In ctlContent.Controls
                            HttpContext.Current.Response.Output.Write(ctlChild.ID.ToString & "<br />")
                        Next
                    End If
                Next
            End If
        Next