• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 831
  • Last Modified:

How do I use a FindControl method inside a Web User Control?

Hi Experts,

I have a subroutine that finds a web control, then sets its value. (Please see attached code snippet)  

However, the FindControl cannot find the control if I put it on a user control, which I then include on a page.  

If I put this subroutine inside the page, instead of the user control, the subroutine works.

How do I find controls in a page from inside a user control?


Public Sub Set_Form_Field(ByVal in_ControlID, ByVal in_Value)
        'sets the value of the form field regardless of web control type. 
        If Not IsNothing(FindControl(in_ControlID)) Then
            Dim ctrl As Control
            ctrl = FindControl(in_ControlID)
            If TypeOf ctrl Is TextBox Then
                Dim txt As TextBox
                txt = CType(ctrl, TextBox)
                txt.Text = in_Value
            End If
            If TypeOf ctrl Is HiddenField Then
                Dim hdn As HiddenField
                hdn = CType(ctrl, HiddenField)
                hdn.Value = in_Value
            End If
            If TypeOf ctrl Is ListBox Then
                Dim cmb As ListBox
                cmb = CType(ctrl, ListBox)
                cmb.SelectedValue = in_Value
            End If
            If TypeOf ctrl Is Label Then
                Dim lbl As Label
                lbl = CType(ctrl, Label)
                lbl.Text = in_Value
            End If
            If TypeOf ctrl Is CheckBox Then
                Dim chk As CheckBox
                If in_Value = "True" Then
                    chk = CType(ctrl, CheckBox)
                    chk.Checked = True
                End If
            End If
        End If
    End Sub

Open in new window

1 Solution
The FindControl method searches only inside its container by default. If its in a User Control, the User Control is its container, so it won't look outside the User Control.

You can tell it which container to search. In this case you want the Page, so you call Page.FindControl("blah") and it will find "blah" on the Page.
crickpaoloAuthor Commented:
Works Great!  Thanks man.
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.

Join & Write a Comment

Featured Post

Cloud Class® Course: Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now