C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Reviews   Communities   Interview   Jobs   Projects   Training   Your Ad Here    
Silverlight Games | Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Polls | Revenue Sharing | Lobby | Gift Shop |


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...






Resources » Code Snippets » ASP.NET GridView »

Date Validation in GridView


Posted Date: 14 Oct 2009    Resource Type: Code Snippets    Category: ASP.NET GridView
Author: Ramesh SMember Level: Gold    
Rating: 1 out of 5Points: 35



Date Validation in GridView



Introduction



I will explain about how to validate date entered in a TextBox control inside a GridView. Sometimes you may need to capture DateTime value in a TextBox inside a GridView control and need to validate before saving to database. This validation will happen when clicking a button, for example, clicking a Save button.

Logic



Here I have validated the date value using server side C# code. The following logic is used to perform the validation.

1. The IsValidDate() function in this code snippet accepts a date value given in string and returns true or false after validating the input.

2. Inside IsValidateDate() function, there are two validation are performed. The first validation checks whether the value is in dd/mm/yyyy format using Regular Expression. It returns false if the format is not valid and the execution does not continue.

3. If the first validation is successful, the second validation in IsValidateDate () checks whether the date value is a valid date using British format. I have used System.IFormatProvider class to do this.

4. The validation is then called in the click event of the btnSave control. The value of the txtDOJ control in each row of the GridView is extarcted using a for loop and checked whether the value entered in the TextBox is a valid date by calling IsValidateDate() function. If the validation fails for a particular GridView row, it will display the row number where the date validation fails.

Code Snippet – aspx



The following aspx code snippet has a GridView and CustomValidator. The date value is captured in a TextBox in a TemplateField of the GridView. The CustomValidator is used to display error message after validation.


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DemoPage28.aspx.cs" Inherits="DemoPage28" %>

<!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>
<table width="100%">
<tr>
<td>
<asp:CustomValidator ID="cvValidateDate" runat="server" ErrorMessage="CustomValidator"></asp:CustomValidator>
</td>
</tr>
<tr>
<td>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
PageSize="5">
<Columns>
<asp:BoundField DataField="EmpCode" HeaderText="Employee Code">
<ItemStyle Width="125px" />
</asp:BoundField>
<asp:BoundField DataField="EmpName" HeaderText="Name">
<ItemStyle Width="250px" />
</asp:BoundField>
<asp:TemplateField HeaderText="DOJ">
<ItemTemplate>
<asp:TextBox ID="txtDOJ" Width="120px" Text='<%#DataBinder.Eval(Container.DataItem, "DOJ") %>'
runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
<tr>
<td>
<asp:Button ID="btnSave" runat="server" Text="Save" onclick="btnSave_Click" />
</td>
</tr>
</table>
</div>
</form>
</body>
</html>



Code Snippet – C#



The following server side code in C# has code to populate the GridView with sample data, IsValidateDate() function and Click event of Save button.


using System;
using System.Web.UI.WebControls;
using System.Data;
using System.Text.RegularExpressions;


public partial class DemoPage28 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridView();
}
}

private void BindGridView()
{
DataTable dtEmp = new DataTable();

dtEmp.Columns.Add("EmpCode", System.Type.GetType("System.Int16"));
dtEmp.Columns.Add("EmpName", System.Type.GetType("System.String"));
dtEmp.Columns.Add("DOJ", System.Type.GetType("System.DateTime"));

dtEmp.Rows.Add(new object[] { 1001, "Kannan", null });
dtEmp.Rows.Add(new object[] { 1002, "Arun", null });
dtEmp.Rows.Add(new object[] { 1003, "Jackson", null });
dtEmp.Rows.Add(new object[] { 1004, "Raja", null });
dtEmp.Rows.Add(new object[] { 1005, "John", null });
dtEmp.Rows.Add(new object[] {1006, "Dinesh", null});

dtEmp.Rows.Add(new object[] { 1007, "Kannan", null });
dtEmp.Rows.Add(new object[] { 1008, "Arun", null });
dtEmp.Rows.Add(new object[] { 1009, "Jackson", null });
dtEmp.Rows.Add(new object[] { 1010, "Raja", null });
dtEmp.Rows.Add(new object[] { 1011, "John", null });
dtEmp.Rows.Add(new object[] { 1012, "Dinesh", null });

GridView1.DataSource = dtEmp;
GridView1.DataBind();
}
protected void btnSave_Click(object sender, EventArgs e)
{
foreach (GridViewRow grow in GridView1.Rows)
{
string strDate = (grow.FindControl("txtDOJ") as TextBox).Text;
if (!String.IsNullOrEmpty(strDate) && !IsValidDate(strDate))
{
cvValidateDate.ErrorMessage = "Invalid date entered in row number " + (grow.RowIndex + 1);
cvValidateDate.IsValid = false;
return;
}
}
}

public static bool IsValidDate(string date)
{
try
{
StringBuilder sb = new StringBuilder();
sb.Append(@"\b([0-9]{1,2}[\s]?[\-/\.\–][\s]?[0-9]{1,2}[\s]?[\-/\.\–][\s]?");
sb.Append(@"[0-9]{2,4})\b|\b(([0-9]{1,2}[TtHhSsRrDdNn]{0,2})[\s]?[\-/\.,\–]?[\s]");
sb.Append(@"?([Jj][Aa][Nn][Uu]?[Aa]?[Rr]?[Yy]?|[Ff][Ee][Bb][Rr]?[Uu]?[Aa]?[Rr]?[Yy]?");
sb.Append(@"|[Mm][Aa][Rr][Cc]?[Hh]?|[Aa][Pp][Rr][Ii]?[Ll]?|[Mm][Aa][Yy]|[Jj][Uu][Nn][Ee]?");
sb.Append(@"|[Jj][Uu][Ll][Yy]?|[Aa][Uu][Gg][Uu]?[Ss]?[Tt]?|[Ss][Ee][Pp][Tt]?[Ee]?[Mm]?");
sb.Append(@"[Bb]?[Ee]?[Rr]?|[Oo][Cc][Tt][Oo]?[Bb]?[Ee]?[Rr]?|[Nn][Oo][Vv][Ee]?[Mm]?[Bb]?");
sb.Append(@"[Ee]?[Rr]?|[Dd][Ee][Cc][Ee]?[Mm]?[Bb]?[Ee]?[Rr]?)[\s]?[\-/\.,\–]?[\s]?[']?([0-9]");
sb.Append(@"{2,4}))\b|\b(([Jj][Aa][Nn][Uu]?[Aa]?[Rr]?[Yy]?|[Ff][Ee][Bb][Rr]?[Uu]?[Aa]?[Rr]?");
sb.Append(@"[Yy]?|[Mm][Aa][Rr][Cc]?[Hh]?|[Aa][Pp][Rr][Ii]?[Ll]?|[Mm][Aa][Yy]|[Jj][Uu][Nn][Ee]?");
sb.Append(@"|[Jj][Uu][Ll][Yy]?|[Aa][Uu][Gg][Uu]?[Ss]?[Tt]?|[Ss][Ee][Pp][Tt]?[Ee]?[Mm]?[Bb]?[Ee]?");
sb.Append(@"[Rr]?|[Oo][Cc][Tt][Oo]?[Bb]?[Ee]?[Rr]?|[Nn][Oo][Vv][Ee]?[Mm]?[Bb]?[Ee]?[Rr]?|[Dd][Ee]");
sb.Append(@"[Cc][Ee]?[Mm]?[Bb]?[Ee]?[Rr]?)[\s]?[,]?[\s]?[0-9]{1,2}[TtHhSsRrDdNn]{0,2}[\s]?[,]?[\s]");
sb.Append(@"?[']?[0-9]{2,4})\b");

Regex reDate = new Regex(sb.ToString());

Match mDate = reDate.Match(date);
if (!mDate.Success)
return false;

System.IFormatProvider ifpformat = new System.Globalization.CultureInfo("en-GB", true);
DateTime tempDate = Convert.ToDateTime(date, ifpformat);
if ((tempDate.Year > 1900) && (tempDate.Year < 2100))
return true;
else
return false;

}
catch (System.FormatException)
{
return false;
}
}


}



Attachments

  • Date Validation Source (33886-14136-DateValidation.zip)


  • Responses


    No responses found. Be the first to respond and make money from revenue sharing program.

    Feedbacks      
    Popular Tags   What are tags ?   Search Tags  
    Sign In to add tags.
    Date Validation in GridView  .  

    Post Feedback


    This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
    You must Sign In to post a response.
    Next Resource: Export GridView To Excel/word Using asp.net
    Previous Resource: Delete selected rows in different pages of gridview control using Asp.net
    Return to Discussion Resource Index
    Post New Resource
    Category: ASP.NET GridView


    Post resources and earn money!
     
    More Resources



    dotNet Slackers

    About Us    Contact Us    Privacy Policy    Terms Of Use