Using Check Boxes in asp.net

No.of Views794
Bookmarked0 times
Downloads 
Votes0
By  Dorababu   On  01 Jun 2010 07:06:47
Tag : ASP.NET , ASP.NET Controls
In this article i would like to cover how to use check box control with proper validations.
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

Introduction

The basic look and feel of the default form is as follows in this for all  the controls on the left hand side there are some paricular validations like required field, regular expression.

Image Loading

 

Image Loading

 Raising Validations: This one is known to all. Raising some validations against each text boxes.  

Image Loading

For phone number i have taken 2 validations one is required field and another is regular expression field to allow only 10 digits for phone number. For this you can also set your text box property  as MAXLENGTH = 10.

 Now comes an interesting one if i enter some characters in place of numbers in textbox i would like to raise an alert or simply i should not allow the user to enter illegal characters other than numbers. 

Sample screen

Image Loading

This one looks good the script i used for this is.

<script type="text/javascript">function NumberOnly(){var AsciiValue=event.keyCodeif((AsciiValue>=48 && AsciiValue<=57) || (AsciiValue==8 || AsciiValue==127)){event.returnValue=true;}else{alert('Only Numbers');event.returnValue=false;}}</script>

In the textbox simple assign onkeypress="return NumberOnly()" so that it will raise an alert when ever user enters illegal character.If u does not want to raise an alert message simply comment the alert function.

 Now if i check the check box provided i would like to fill the other text boxes provided with the same values . And the values are passed only if all the validation conditions passes. 

The final output will be a s follows 

Image Loading

 Code for the complete article

Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_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>Untitled Page</title>

    <script type="text/javascript">
    function NumberOnly()
        {
           var AsciiValue=event.keyCodeif((AsciiValue>=48 && AsciiValue<=57) || (AsciiValue==8 || AsciiValue==127))
            {event.returnValue=true;
             
            }else{
                alert('Only Numbers');event.returnValue=false;
                }
        }
    </script>

</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:Label ID="Label1" runat="server" Style="left: 59px; position: absolute; top: 120px"Text="Name"></asp:Label>
            <asp:Label ID="Label2" runat="server" Style="left: 51px; position: absolute; top: 161px"Text="Lastname"></asp:Label>
            <asp:TextBox ID="txtName" runat="server" Style="left: 126px; position: absolute;
                top: 119px"></asp:TextBox>
            <asp:TextBox ID="txtLname" runat="server" Style="left: 127px; position: absolute;
                top: 155px"></asp:TextBox>
            <asp:TextBox ID="txtPhonenumber" runat="server" onkeypress="return NumberOnly()"MaxLength="10" Style="left: 129px; position: absolute; top: 194px"></asp:TextBox>
            <asp:TextBox ID="txtphno" runat="server" onkeypress="return NumberOnly()" MaxLength="10"Style="left: 596px; position: absolute; top: 191px"></asp:TextBox>
            <asp:Label ID="Label3" runat="server" Style="left: 38px; position: absolute; top: 196px"Text="Phonenumber"></asp:Label>
            &nbsp;
            <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="Last Name required"Style="left: 305px; position: absolute; top: 154px" ValidationGroup="g" ControlToValidate="txtLname"></asp:RequiredFieldValidator>
            <asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server" ControlToValidate="txtLname1"ErrorMessage="Last Name required" Height="21px" Style="left: 759px; position: absolute;
                top: 144px" ValidationGroup="g1" Width="133px"></asp:RequiredFieldValidator>
            <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="txtPhonenumber"ErrorMessage="Phone Number Required" Style="left: 310px; position: absolute;
                top: 195px" ValidationGroup="g"></asp:RequiredFieldValidator>
            <asp:RequiredFieldValidator ID="RequiredFieldValidator6" runat="server" ControlToValidate="txtphno"ErrorMessage="Phone Number Required" Style="left: 760px; position: absolute;
                top: 184px" ValidationGroup="g1" Width="158px"></asp:RequiredFieldValidator>
            <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtName"ErrorMessage="Name required" Style="left: 304px; position: absolute; top: 112px"ValidationGroup="g"></asp:RequiredFieldValidator>
            <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ControlToValidate="txtName1"ErrorMessage="Name required" Height="23px" Style="left: 750px; position: absolute;
                top: 102px" ValidationGroup="g1" Width="106px"></asp:RequiredFieldValidator>
            &nbsp; &nbsp;&nbsp;
            <asp:CheckBox ID="CheckBox1" runat="server" ValidationGroup="g" Style="left: 243px;
                position: absolute; top: 244px" OnCheckedChanged="CheckBox1_CheckedChanged" AutoPostBack="true" CausesValidation="True" />
            <asp:Button ID="Button1" runat="server" Style="left: 169px; position: absolute; top: 240px"Text="Button" ValidationGroup="g" OnClick="Button1_Click" />
            <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="txtPhonenumber"ErrorMessage="Must be 10 Digits" ValidationExpression="\d{10}" ValidationGroup="g"Style="left: 313px; position: absolute; top: 215px"></asp:RegularExpressionValidator>
            <asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server" ControlToValidate="txtphno"ErrorMessage="Must be 10 Digits" Style="left: 771px; position: absolute; top: 207px"ValidationExpression="\d{10}" ValidationGroup="g1" Width="134px"></asp:RegularExpressionValidator>
            <asp:Label ID="Label4" runat="server" Style="left: 474px; position: absolute; top: 115px"Text="Name"></asp:Label>
            <asp:Label ID="Label5" runat="server" Style="left: 473px; position: absolute; top: 162px"Text="Last Name"></asp:Label>
            <asp:Label ID="Label6" runat="server" Style="left: 473px; position: absolute; top: 196px"Text="Phone Number"></asp:Label>
            <asp:TextBox ID="txtName1" runat="server" Style="left: 583px; position: absolute;
                top: 107px"></asp:TextBox>
            <asp:TextBox ID="txtLname1" runat="server" Style="left: 593px; position: absolute;
                top: 152px"></asp:TextBox>
        </div>
    </form>
</body>
</html>

Default.aspx.cs

using System;
using System.Data;
using System.Configuration;
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;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{protected void Page_Load(object sender, EventArgs e)
    {

    }protected void Button1_Click(object sender, EventArgs e)
    {//Page.Validate();// if (Page.IsValid)//{SqlConnection con =new SqlConnection(ConfigurationManager.AppSettings["sqlcon"].ToString());
            SqlCommand cmd = new SqlCommand("empins1", con);
            cmd.CommandType = CommandType.StoredProcedure;

            cmd.Parameters.Add("@FirstName", SqlDbType.VarChar, 50);

            cmd.Parameters.Add("@Lastname", SqlDbType.VarChar, 50);

            cmd.Parameters.Add("@Phno", SqlDbType.Int);


            cmd.Parameters["@FirstName"].Value = txtName.Text;

            cmd.Parameters["@Lastname"].Value = txtLname.Text;

            cmd.Parameters["@Phno"].Value = Convert.ToInt64(txtPhonenumber.Text);

            con.Open();

            cmd.ExecuteNonQuery();

            con.Close();//}}protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
    {if (CheckBox1.Checked)
        {
            txtphno.Text = txtPhonenumber.Text;
            txtName1.Text = txtName.Text;
            txtLname1.Text = txtLname.Text;
            txtLname1.Enabled = false;
            txtName1.Enabled = false;
            txtphno.Enabled = false;
        }else{
            txtphno.Enabled = true;
            txtLname1.Enabled = true;
            txtName1.Enabled = true;
            txtphno.Text = "";
            txtLname1.Text = "";
            txtName1.Text = "";
        }
    }
}
 

Use the store procedure for inserting data

set ANSI_NULLS ONset QUOTED_IDENTIFIER ONgoALTER procedure [dbo].[empins1](@Firstname varchar(50),@Lastname varchar(50),@Phno int)asinsert into samplevalues(@Firstname,@Lastname,@Phno)RETURN

Hope it helps.Happy Coding.Thank for reading.

 
Sign Up to vote for this article
 
About Author
 
Dorababu
Occupation-Software Engineer
Company-Mudiam
Member Type-Fresh
Location-India
Joined date-15 May 2010
Home Page-
Blog Page-
 
 
Other popularSectionarticles
Comments
By:RRaveenDate Of Posted:10/5/2010 11:06:57 PM
You can set
Hi, You able set by html or or can you set in code as well under the page init event add this code chkBox.AutoPostBack=true; its will work for you
By:AnuDate Of Posted:10/5/2010 9:34:02 PM
Properties of checkbox
In the default.aspx, I cannot set properties like OnCheckedChanged , Autopostback etc. What could be hte reason?
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top