views:

457

answers:

3

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.

+3  A: 

The only way I know to do this is to do this in your user control class:


[ValidationProperty("Foo")]
public class MyUserControl : UserControl
{
     public string Foo
     {
          get { return(yourDropDown.SelectedValue); }
     }
}

And then in the page you place the user control on:


<asp:RequiredFieldValidator ControlToValidate="yourUserControlName" runat="server" ErrorMessage="You are required to make a selection" />

Not quite the same thing, but that's the only workaround that I know.

mgroves
Thank you for the help.
mkelley33
This one worked for me, however it does a postback before it validates which is unlike the other RequiredFieldValidators that are validating the regular textboxes, any suggestions on getting them to work all at the same time.
Adam Smith
Did you Chris Mullins's answer and expose the whole dropdown instead of just the SelectedValue? Other than that, you may have to write some custom javascript.
mgroves
+4  A: 

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;
}
Chris Mullins
Thank you! I couldn't get it to work for a user control nested within a user control, but I appreciate all of the help.
mkelley33
A: 

I think the best way to validate user control is to have public method inside your user control:

public void Validate() {
  reqRecipientName.Validate();
  reqRecipientMail.Validate();
  valRecipientMail.Validate();
  reqRecipientPhone.Validate();
}

where reqRecipientName, reqRecipientMail... are ID of validators (they are also insice ascx). And then on Page inside submit method call controlId.Validate(); This works for me.

Adam