Handling RequiredFieldValidator inside of a User Control

孤街浪徒 提交于 2019-12-13 14:41:31

问题


I have a User Control which consists of a TextBox with a few extras, but for purposes of this example just assuming it's a plain TextBox will be sufficient. I am calling this User Control from a Web Form and would like to be able to use a RequiredFieldValidator that basically would function the same as if I used it on a TextBox on the web form. How do I configure my User Control to handle this?

EDIT:

DatePicker.ascx

<asp:TextBox runat="server" ID="myControlTB">

DatePicker.ascx.cs

[ValidationProperty("Text")]
public partial class DatePicker : System.Web.UI.UserControl
{
    public String Text { get { return myControlTB.Text; } set { myControlTB.Text = value; } }
    protected void Page_Load(object sender, EventArgs e)
    {

    }
}

WebForm.aspx

<cu:UserControl runat="server" ID="myControl">
<asp:RequiredFieldValidator runat="server" errormessage="This is a required field." ControlToValidate="myControl">
<asp:Button ID="btnSubmit" runat="server" Text="Submit" onclick="btnSubmit_Click" />

WebForm.aspx.cs

protected void btnSubmit_Click(object sender, EventArgs e)
{
    Page.Validate();
    if (Page.IsValid)
    {
        // e-mail the form
    }

回答1:


You would need to set the ValidationProperty attribute on the control and expose the Textbox Text property as a control property

 [ValidationProperty("Text")]
 public partial class Control
 {
    public string Text 
    {
        get { return textbox.Text;}
    }

 }



回答2:


Add a property to the user control:

public string TextBoxID
{
   get { return myControlTB.ClientID; }
}

And then for the validation control, programmably set it from code:

void Page_Load(..)
{
    this.rfv.ControlToValidate = this.uc.TextBoxID;
}

I actually don't know if it will work this way, but you could also try UniqueID, or the ID directly, and see if any of that makes a difference.

Either that, or change TextBoxID to TextboxText, and return myControlTB.Text, and add a [ValidationProperty("TextBoxText")] on the control, and set the ControlToValidate on the required field validator to the user control.

Try one of those approaches,

HTH.



来源:https://stackoverflow.com/questions/4829758/handling-requiredfieldvalidator-inside-of-a-user-control

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!