[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 823
  • 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.

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

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