Search code examples
asp.netascx

Access control from .aspx in .ascx


I have a custom user control that I made called OrderForm.ascx. I also have an .aspx file that utilizes the OrderForm control.

I want to access a control on the .aspx file from the OrderForm control. Is there a way to do this?


Solution

  • You could use the FindControl method in the user control like this:

    Label label = Page.FindControl("Label1") as Label;
    if (label != null)
        string labelText = label.Text;
    

    As a note on the above, depending on where the Label is in the page, you may need to use recursion to find the Label.

    You could also create a property on the page that returns the text of the Label:

    public string LabelText
    {
        get { return Label1.Text; }
    }
    

    To access the property from the user control, here are two options:

    Option #1

    string labelText = ((PageName)Page).LabelText;
    

    Option #2

    string labelText = Page.GetType().GetProperty("LabelText").GetValue(Page, null).ToString();