Search code examples
c#asp.netvalidationuser-controlsascx

How do I add an ASP.NET control inside an ASCX to an external RequiredFieldValidator programmatically?


I have a drop-down list inside a user control (ASCX) that I want to validate from the page on which I've placed the ASCX, but when I set the ControlToValidate to the drop-down list the page complains that it can't be found. Thanks for any help/suggestions.


Solution

  • Expose the dropdown list with a public property in your user control:

    public DropDownList DropDownToValidate
        {
            get
            {
                return ddlTest;
            }
        }
    

    Then use the UniqueID of the exposed Dropdown to set the control to validate in the page load of the page on which you dropped the user control:

    protected void Page_Load(object sender, EventArgs e)
    {
    
        RequiredFieldValidator1.ControlToValidate = WebUserControl1.DropDownToValidate.UniqueID;
    }