3

I am trying to validate two checkboxes. One of them must be checked in order for the form to be valid. I would like to use a CustomValidator control, and validate on the server.

(This .ascx page is a form that is displayed on a different .aspx page.)

First I put in the checkboxes and a CustomValidator control on my .ascx page. Like this:

<tr>
        <td colspan="3">
            <input type="checkbox" runat="server" name="EmailCourse" class="" id="EmailCourse" value="" />
                Email course
<asp:CustomValidator id="CustomValidator1" runat="server" ErrorMessage="No checkbox checked" 
                 OnServerValidate="validateCheckBoxes_ServerValidate">
                </asp:CustomValidator>

        </td>
    </tr>
<tr>
        <td colspan="3">
            <input type="checkbox" runat="server" name="SpecialReport" class="" id="SpecialReport"  value="" />
                Special report
        </td>
    </tr>

Then, I added the validateCheckBoxes_ServerValidate function in the code-behind, on the .ascx.cs page, like this:

            protected void validateCheckBoxes_ServerValidate(object source, ServerValidateEventArgs args)
        {
            if (!EmailCourse.Checked && !SpecialReport.Checked)
                args.IsValid = false;
            else
                args.IsValid = true;

    }

When I try to open the page that uses this form on my local site to see what it looks like, I get an error, like this:

Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

Compiler Error Message: CS1061: 'ASP.common_controls_specialreportform_ascx' does not contain a definition for 'validateCheckBoxes_ServerValidate' and no extension method 'validateCheckBoxes_ServerValidate' accepting a first argument of type 'ASP.common_controls_specialreportform_ascx' could be found (are you missing a using directive or an assembly reference?)

And:

error CS1061: 'ASP.common_controls_specialreportform_ascx' does not contain a definition for 'validateCheckBoxes_ServerValidate' and no extension method 'validateCheckBoxes_ServerValidate' accepting a first argument of type 'ASP.common_controls_specialreportform_ascx' could be found (are you missing a using directive or an assembly reference?)

Does anyone know what the cause of this error is? I'm new at asp.net and am having trouble with this.

Thanks!

3
  • 1
    Are you sure the code-behind handler is actually in the class that is being referenced by the ASCX page? Commented Jun 18, 2012 at 9:40
  • @freefaller is right, looks like class reference or namespace problem to me too. Commented Jun 18, 2012 at 9:43
  • Good spot by harry180 in his answer... user1463201, can you confirm whether the checkboxes are on the parent ASPX page and the code is behind the ASCX page (as per your question), or is that a typo and the checkboxes are also on the ASCX page? Commented Jun 18, 2012 at 10:11

4 Answers 4

2

You put validateCheckBoxes_ServerValidate in *.ascx.cs when it should be on ur aspx.cs . On ascx.cs you can't refer the control it is on Parent like this.

put this code to ur aspx.cs file:

protected void validateCheckBoxes_ServerValidate(object source, ServerValidateEventArgs args)
{
        if (!EmailCourse.Checked && !SpecialReport.Checked)
            args.IsValid = false;
        else
            args.IsValid = true;

}

Edit:

Your custom Validator on ascx should seems like:

<asp:CustomValidator id="CustomValidator1" runat="server" ErrorMessage="No checkbox  checked" ControlToValidate="EmailCourse" OnServerValidate="validateCheckBoxes_ServerValidate"/>

without this ControlToValidate attribute server don't know which control u would like to validate.

Edit2:

Did u try to use change <input type="checkbox"/> to <asp:CheckBox />? and tell me how this should be Validate after btn click or after checkbox checked/unchecked?

Edit3:

Check that in your .ascx.designer.cs EmailCourse got proper Type.

Edit4:

When u have <asp:CheckBox .../> on your *.ascx file u should have in your ascx.designer.cs this type protected global::System.Web.UI.WebControls.CheckBox EmailCourse

Please let me know if this help.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the help! Actually, I had a typo, which I have edited in my original question. The checkboxes are on the .ascx page, and the validateCheckBoxes_ServerValidate function is in the code-behind, on the .ascx.cs page. What do you think the issue is that is stopping this from working?
I tried doing <td colspan="3"> <asp:CheckBox id="EmailCourse" runat="server" Text="Email course -- Send me one tip a day."></asp:CheckBox> <asp:CustomValidator id="CustomValidator1" runat="server" ErrorMessage="No checkbox checked" ControlToValidate="EmailCourse" OnServerValidate="validateCheckBoxes_ServerValidate"></asp:CustomValidator> </td> but I got an asp.net runtime error: "The base class contains the field EmailCourse... but its type... is not compatible" Thanks Harry180 - I appreciate your help!
The type I have for EmailCourse in .ascx.designer.cs is: protected global::System.Web.UI.HtmlControls.HtmlInputCheckBox EmailCourse; That looks fine to me...
did it help? if yes check this as an answer
1

Qs your question seems to be answered, I want to show you how you can write less

protected void validateCheckBoxes_ServerValidate(object source, ServerValidateEventArgs args)
{
args.IsValid = (!EmailCourse.Checked && !SpecialReport.Checked);
}

This is the same than what you wrote except this is in one line

Comments

0

I've maked a working example of what u tryed to do @user1463201

here is .aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="ValidationExample._Default" %>

  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

   <html xmlns="http://www.w3.org/1999/xhtml">
   <head runat="server">
   <title></title>
   </head>
   <body>
      <form id="form1" runat="server">
        <div>
          <asp:ValidationSummary runat="server" ID="myValidationSummary" ValidationGroup="validation"/>
           <table>
             <tr>
                <td>
                  <asp:CheckBox runat="server" ID="cbxEmailCourse" Text="Email course" EnableViewState="True" AutoPostBack="True"/>
              </td>
            </tr>
            <tr>
              <td>
                <asp:CheckBox runat="server" ID="cbxSpecialReport" Text="Special report"/>
              </td>
           </tr>
           <tr>
              <td>
                <asp:TextBox Visible="False" Text="t" runat="server" ID="txtValid" ValidationGroup="validation"></asp:TextBox>
              </td>
              <td>
                <asp:Button runat="server" ID="btnValid" Text="Validate form" ValidationGroup="validation" OnClick="btnValid_Click"/>
                <asp:CustomValidator runat="server" ID="cValidator" ControlToValidate="txtValid" ValidationGroup="validation" OnServerValidate="cValidator_Validate"></asp:CustomValidator>
              </td>
          </tr>
      </table>
   </div>
  </form>
  </body>
 </html>

and aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace ValidationExample
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void cValidator_Validate(object source, ServerValidateEventArgs args)
        {
            args.IsValid = cbxEmailCourse.Checked && cbxSpecialReport.Checked;
        }

        protected void btnValid_Click(object sender, EventArgs e)
        {
            if (!Page.IsValid)
               Response.Write("Page are not Validate");
        }

    }
 }

I hope my work will help somebody:) enjoy

Comments

0

OK. So here's what worked:

As harry180 suggested, I did need to switch the input-type="CheckBox" to asp:CheckBox.

This triggered a run-time error, which I commented about above. The run-time error was because I had not recompiled the solution after making the change, in order that the ascs.designer.cs file be modified.

After recompiling, the code works.

1 Comment

Does anyone know why it takes so long for the page to validate the checkbox? I thought maybe it was because this is not on the client side, so I added client side validation, too. This did not help it take a shorter time. It seems like it is not doing the client side validation that I added. Can this be? Does it first do the server side validation? That would be strange. Or is my code for client side val wrong? Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.