Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

validate field if checkbox.checked 2

Status
Not open for further replies.

devRyan

Programmer
Sep 1, 2006
104
US
Hi all,

I was wondering how to require a text field on the condition that a checkbox is checked.

I have a text field that collects a completion date with a related checkbox that denotes isComplete. I want to set a requiredField validator on the text field.

I've added a required field validator to the text field and set it to enabled=false, and in the code behind when I confirm that the check box is checked, I set the requiredField validator to enabled=true, then call the validate function for the validator, like so:

if (checkbox.chacked)
{
this.reqValDateCompleted = true;
this.reqValDateCompleted.Validate();
}

but nothing happens, which makes me think I'm using the wrong methods for doing this.

Can someone point me in the right direction, please?
 
Set the check box's autopostback to true.
Write code in the checkbox default event handler:

((RequiredFieldValidator)this.findcontrol("reqValDateCompleted")).Enabled = CheckBoxName.Checked();


I have tested it in VB.. and i hope my conversion is correct and work for c#.
 
Thanks for responding.

When I run this I get a NullReferenceException was unhandled by user code: Object reference not set to an instance of an object; on the line:

((RequiredFieldValidator)this.FindControl("reqValDateCompleted")).Enabled = isResolved.Checked;

The field names are correct.
 
The default event handler is as follow:

protected void chkIsResolved_CheckedChanged(object sender, EventArgs e)
{
((RequiredFieldValidator)this.FindControl("reqValDateCompleted")).Enabled = chkIsResolved.Checked;
}
 
private void isResolved_CheckedChanged(object sender, System.EventArgs e)
{
((RequiredFieldValidator)this.FindControl("reqValDateCompleted")).Enabled = isResolved.Checked;
}


Works for me.
Make sure to set the autopostback of the isResolved.
 
I've got autopostback set to true. I tried using private instead of protected in the declaration, but I get a compilation error saying that the method can't be reached due to its protection level.
 
Please write the whole compilation error message you get.
 
Error 1 'EditBugs.chkIsResolved_CheckedChanged(object, System.EventArgs)' is inaccessible due to its protection level C:\Documents and Settings\Administrator\My Documents\Visual Studio 2005\WebSites\BugTracker\editBug.aspx 74
 
I'm still having problems with this. Any other insight?
 
I cant think of something helpful right now. I have not come across this kind of error.
I'll have this in mind.
Sorry

(This works for me fine. Did you start this project in these days? I mean, can you upload it somewhere so (others and) i can download it and have a closer look?)

Errr, is this prohibited by the tektips forums ?
 
It's not prohibited but as long as you paste the relevant code on here so that others can see it will be fine.


____________________________________________________________

Need help finding an answer?

Try the Search Facility or read FAQ222-2244 on how to get better results.

 
You are right.
I don't know what part of code to ask devRyan to paste.
 
Here is the frontside
Code:
<tr>
    <td class="fieldName">
      Date Completed:
    </td>
    <td>
      <asp:Textbox ID="txtDateCompleted" runat="server" />
      <asp:CompareValidator ID="comValDateCompleted" runat="server" Display="Dynamic"
      ControlToValidate="txtDateCompleted" SetFocusOnError="true" Operator="DataTypeCheck" Type="Date"
      ErrorMessage="Please enter a valid date for the date completed">*</asp:CompareValidator>
      <asp:RequiredFieldValidator ID="reqValDateCompleted" runat="server" Enabled="false" Display="Dynamic"
      ErrorMessage="Please enter a completion date." SetFocusOnError="true" ControlToValidate="txtDateCompleted"
      >*</asp:RequiredFieldValidator>
      <br />
      Is Resolved:&nbsp;
      <asp:CheckBox ID="chkIsResolved" runat="server" AutoPostBack="true" OnCheckedChanged="chkIsResolved_CheckedChanged" />      
    </td>
  </tr>

...the code behind for the check box

Code:
protected void chkIsResolved_CheckedChanged(object sender, EventArgs e)
  {
    ((RequiredFieldValidator)this.FindControl("reqValDateCompleted")).Enabled = chkIsResolved.Checked;
  }

...and the libraries included in the .cs file

Code:
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

When I run it, I get a NullReferenceException was not handle by user code: "Object reference not set to an instance of an object."

I would really rather that it fired onSubmit, but that should be easy enough to figure out once get the OnCheckedChanged worked out.

Thanks
 
I've tried to rewrite it as, but I get the same result:

Code:
 RequiredFieldValidator reqVal = new RequiredFieldValidator();
    reqVal = ((RequiredFieldValidator)this.FindControl("reqValDateCompleted"));
    reqVal.Enabled = chkIsResolved.Checked;
 
I've created a brand new project and copied the code I've pasted here into it, and it runs fine. I'm digging deeper at the moment.
 
Ok, I've narrowed it down a little more.

My original pages use a master page, so I took my new test project, which worked, and put it in master page format. Now I get the same error on the test project.

 
Here's the full code for my test site. please tell me if you get errors from it. It worked like everyone said it was, until I put it into the masterpage format, which now throws the same error as my main project(which uses master pages).

Master page
Code:
<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>

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

<html xmlns="[URL unfurl="true"]http://www.w3.org/1999/xhtml"[/URL] >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:contentplaceholder id="ContentPlaceHolder1" runat="server">
        </asp:contentplaceholder>
    </div>
    </form>
</body>
</html>

Default aspx
Code:
<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" Title="Untitled Page" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<table>
      <tr>
        <td class="fieldName">
          Date Completed:
        </td>
        <td>
          <asp:Textbox ID="txtDateCompleted" runat="server" />
          <asp:CompareValidator ID="comValDateCompleted" runat="server" Display="Dynamic"
          ControlToValidate="txtDateCompleted" SetFocusOnError="true" Operator="DataTypeCheck" Type="Date"
          ErrorMessage="Please enter a valid date for the date completed">*</asp:CompareValidator>
          <asp:RequiredFieldValidator ID="reqValDateCompleted" runat="server" Enabled="false" Display="Dynamic"
          ErrorMessage="Please enter a completion date." SetFocusOnError="true" ControlToValidate="txtDateCompleted"
          >*</asp:RequiredFieldValidator>
          <br />
          Is Resolved:&nbsp;
          <asp:CheckBox ID="chkIsResolved" runat="server" AutoPostBack="true" OnCheckedChanged="chkIsResolved_CheckedChanged" />      
        </td>
      </tr>
    </table>  
</asp:Content>

default aspx cs
Code:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

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

  }

  protected void chkIsResolved_CheckedChanged(object sender, EventArgs e)
  {
    RequiredFieldValidator reqVal = new RequiredFieldValidator();
    reqVal = ((RequiredFieldValidator)this.FindControl("reqValDateCompleted"));
    reqVal.Enabled = chkIsResolved.Checked;
    reqVal.Validate();
  }
}
 
You have droped a required field validator.
Why "RequiredFieldValidator reqVal = new RequiredFieldValidator();" ?


protected void chkIsResolved_CheckedChanged(object sender, EventArgs e)
{
((RequiredFieldValidator)this.FindControl("reqValDateCompleted")).Enabled = chkIsResolved.Checked;

}


You aldeady have an instance of the validator. Do not use new. You can do it like your way, but NOT create a new one...


RequiredFieldValidator reqVal = ((RequiredFieldValidator)this.FindControl("reqValDateCompleted"));
reqVal.Enabled = chkIsResolved.Checked;
 
Right, I see what you mean. I've changed it as suggested to(below), though it still throws the same error.

Code:
protected void chkIsResolved_CheckedChanged(object sender, EventArgs e)
  {
    RequiredFieldValidator reqVal = ((RequiredFieldValidator)this.FindControl("reqValDateCompleted"));
    reqVal.Enabled = chkIsResolved.Checked;
    reqVal.Validate();
  }
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top