Search code examples
c#asp.netdatalistcustomvalidator

ASP.NET CustomValidator OnServerValidate within datalist?


I need to use a customvalidator for a bunch of textboxes within a datalist, however I'm unsure on how to call the customvalidator's "OnServerValidate" from within the datalist.

So far, I'm creating my customvalidators dynamically within my datalist's ItemDataBound (although I'm open to an alternate way):

protected void dataList_ItemDataBound(object sender, DataListItemEventArgs e)
{
     CustomValidator cv = (CustomValidator) e.Item.FindControl("CustomValidator1");
    cv.ControlToValidate = "txtTextBox1";
    cv.ServerValidate += new EventHandler(CustomValidator1_ServerValidate);
}

But my "cv.ServerValidate" line is throwing an error. I'm not entirely sure how to properly set this up to ensure we have an "OnServerValidate"

Thanks


Solution

  • You don't need to create CustomValidator in runtime, it's much easier to use it inside template. Here is sample code for use inside EditItemTemplate to validate textbox:

    <asp:DataList ID="DataList1" runat="server">
        <EditItemTemplate>
            <asp:TextBox ID="TextBoxNextActionDate" Text='<%# Bind("NextActionDate") %>' runat="server"
                            CssClass="gridTextBoxEdit140"></asp:TextBox>
            <asp:CustomValidator ID="CustomValidator1" runat="server" ControlToValidate="TextBoxNextActionDate"
                            ErrorMessage='<% $resources:AppResource,NotValidDateTime %>' Display="Dynamic"
                            OnServerValidate="DateTimeCustomValidator_ServerValidate"></asp:CustomValidator>
         </EditItemTemplate>
    </asp:DataList> 
    

    And here is handler:

        protected void DateTimeCustomValidator_ServerValidate(object source, ServerValidateEventArgs args)
        {
            DateTime d = new DateTime();
            if (!DateTime.TryParse(args.Value, out d))
            {
                args.IsValid = false;
            }
            else
            {
                args.IsValid = true;
            }
        }
    

    Hope this helps!