CODEDIGEST
Home » Articles
Search
 

Technologies
 

Sponsored links
 

CodeDigest Navigation
 

Technology News
No News Feeds available at this time.
 

Community News
No News Feeds available at this time.
 
DatePicker Control in ASP.Net

By Satheesh Babu
Posted On Jun 04,2009
Article Rating:
Average Rating: 5
No of Ratings: 1
No of Comments: 30
Category: ASP.Net
Print this article.

DatePicker Control in ASP.Net

 

Most often we will get a requirement to capture date input from the users. Normally, we can do this with a textbox and asking user to input the date in a particular format using a help text near by the textbox. We will also have validation function that validates the inputted date for correct format.

Something like the below figure,

Date Picker in ASP.Net

 It will be good and user friendly, if we provide a button next to the textbox which will pop up a calendar for the user to select a date, a datepicker control. This prevents the need to make the user type in a particular format and also will give a better user experience. Well, this can be implemented in various ways. This article will help us to build this control ourselves and also some of the other options available. Moving forward, this article will help us to create DatePicker control in 3 ways,

Ø       Using ASP.Net Calendar control.

Ø       Using Calendar Extender control in AJAX Control Toolkit.

Ø       Using jQuery DatePicker Plug-in.

 

Using ASP.Net Calendar control

1) Drag a TextBox to the WebForm and name it as 'txtDate'.

2) You can either use button control or an IMG to open the calendar.

 

Now write a JavaScript function to open the popup that is containing the Calender control.

function PopupPicker(ctl)

{

var PopupWindow=null;

PopupWindow=window.open('DatePicker.aspx?ctl='+ctl,'','width=250,height=250');

PopupWindow.focus();

}

 

Pass the textbox control name as a query string (here ctl) to the popup, so that the pop up window can populate the textbox control in the parent window with the date selected by you. I have used image button to open the Calendar. Refer the below code,

 

<img src="_images/images.jpg" style="cursor:hand;" onclick="PopupPicker('txtDate')" />

 

Since, we are passing the textbox id as a querystring we can reuse this control in multiple places in our project. Means, just pass the textbox id where you want to populate the date in the onclick function call.

 

Building DatePicker.aspx

1) Drag a Calendar Control into the webform.

2) Get the TextBox Control Name that is coming as query string.

3) Fill the Parent form's textbox with the selected date by using the following JavaScript function.

 

function SetDate(dateValue,ctl)

{

thisForm = window.opener.document.forms[0].elements[ctl].value= dateValue;

self.close();

}

 

Now in clnDatePicker_DayRender Event, write the follow code to call the javascript function 'SetDate'.

 

protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)

 {

string ctrl = Request.QueryString["ctl"];

HyperLink hpl = new HyperLink();

hpl.Text = ((LiteralControl)e.Cell.Controls[0]).Text;

hpl.NavigateUrl = "javascript:SetDate('" + e.Day.Date.ToShortDateString() + "','"+ctrl+"');";

e.Cell.Controls.Clear();

e.Cell.Controls.Add(hpl);

}

 

By default, all the day links rendered by the calendar server control will generate a postback to the server. What we do here is instead of postback, we will call our custom SetDate() JavaScript function.

To do this, we will clear the table cell that contains the day link and replace with a HyperLink control with our javascript function attached to that. Refer the above code.

Execute the page and see it in action.

 

Using Calendar Extender control in AJAX Control Toolkit

The next option to provide a datepicker feature in asp.net is using the Calendar extender control from Ajax control toolkit.

 

How to construct this?

To use this feature, you need to download Ajax control toolkit from here.

Read my article Ajax Control Toolkit – Introduction to integrate and know more about this toolkit.

I assume you have toolkit already installed and integrated in your visual studio.

1.      Drag a textbox control.

2.      Drag a CalenderExtender control.

3.      Set the textbox ID in the TargetControlID property of CalenderExtender control.

<cc1:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">

        </cc1:ToolkitScriptManager>

        <asp:TextBox ID="txtDate" runat="server"></asp:TextBox>

        <cc1:CalendarExtender ID="CalendarExtender1" TargetControlID="txtDate" runat="server">

        </cc1:CalendarExtender>

 

Execute the page. You can see the datepicker control in action similar to below figure.

DatePicker with AJAX Control Toolkit

The drawbacks of this approach are,

1.      This technique has a dependency on ASP.Net AJAX framework and hence it requires the framework to be installed on the production server.

2.      Your page will be heavy due to the ASP.NET Ajax client-side framework scripts.

 

Next, we will see how we can provide datepicker feature using jQuery.

 




Using jQuery DatePicker Plug-in

Using jQuery date picker plug-in is one of the best options if you want to construct a datepicker control in your asp.net projects.

How to use this?

1.      Download the latest version of jQuery library from the jquery.com.

2.      Refer the following faq’s to integrate and use jQuery library in Visual Studio 2008.

What is jQuery? How to use it in ASP.Net Pages?

How to enable jQuery intellisense in Visual Studio 2008?

3.      Download the jQuery datepicker plug-in from here. This plug-in offers multiple features. You can download the customized version of the plug-in by selecting the features you require on the download page. The option UI Core is required for any feature you download. You can select the themes you require from the theme dropdown on the download page. Hence, the download includes the files that are necessary for the themes as well.

4.      Unzip and copy the script (plug-in) into your solution and add a reference to the plug-in in your aspx page. Also, you need to copy the css folder into your solution for the themes.

5.      Drag a textbox control from the toolbox into your aspx page.

6.      To make the jQuery calendar to appear you need to call the datepicker() function. Refer the below code,

<head runat="server">

    <title></title>

    <link type="text/css" href="css/smoothness/jquery-ui-1.7.1.custom.css" rel="stylesheet" />

     <script src="_scripts/jquery-1.3.2.min.js" type="text/javascript"></script>

     <script src="_scripts/jquery-ui-1.7.1.custom.min.js" type="text/javascript"></script>

    <SCRIPT type="text/javascript">

        $(function() {

         $("#txtDate").datepicker();      

        });  

       </SCRIPT>

</head>

<body>

    <form id="form1" runat="server">

    <div>

    <asp:TextBox ID="txtDate" runat="server"></asp:TextBox>

    </div>   

    </form>

</body>

Execute the page and you can see the jQuery calendar appearing when we click on the textbox. Refer the below figure,

DatePciker using jQuery DatePicker plugin

Refer here to know more and customize the jQuery datepicker.

Some of the advantages of using this control are,

Ø       It’s purely client side and requires no execution in serverside.

Ø       Can do more customization.

Ø       Since, this also downloads a javascript library to the client side we can try using google’s CDN for improved caching, etc.

 

Downloads

Download Source 

Conclusion

Thus, we have seen 3 different ways of providing data picker feature in our ASP.Net project. You can use any of the approach that fits your need. Download the source attached with article and see it in action.

Happy coding!!

 

Similar Articles
You can contribute to CodeDiget.Com:
Donate to CodeDigest.com
Article Feedback
Comments
Nice article
Nice article, if you want you can see more great datepicker control in this link:
https://demos.shieldui.com/aspnet/datepicker/basic-usage
wqw
saa
Multiple dates
Hello.. it seems like a long shot to post something here.. but well.. the first solution (Datepicker.aspx) doesn't work for multiple dates... It fills the field but it delets the text from other fields and I'm not able to find a solution.

Any help?
Cool
Good Tool
how to get value in server side
it's me again,

it's working now. just remove readonly proterty for the textbox
how to get value in server side
this is my code

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link type="text/css" href="../css/start/jquery-ui-1.8.14.custom.css" rel="stylesheet" />
<script type="text/javascript" src="../js/jquery-1.5.1.min.js"></script>
<script type="text/javascript" src="../js/jquery-ui-1.8.14.custom.min.js"></script>
<script type="text/javascript">
$(function(){
$("input[id$=tbFrom]").datepicker({
inline : true,
dateFormat :'dd-M-yy',
effect :'slideDown',
minDate :"-48M -0D",
maxDate :"+0M +0D",
showAnim : 'slideDown',
// autoSize : true
// showOtherMonths : true,
// selectOtherMonths : true,
numberOfMonths : 3,
showButtonPanel : true
});
$("input[id$=tbTo]").datepicker({
inline : true,
dateFormat :'dd-M-yy',
effect :'slideDown',
minDate :"-48M -0D",
maxDate :"+0M +0D" ,
showAnim : 'slideDown',
// autoSize : true
// showOtherMonths : true,
// selectOtherMonths : true,
numberOfMonths : 3,
showButtonPanel : true
});
});
</script>
<asp:TextBox ID="tbFrom" Font-Names="Arial" Font-Size="8pt" Width="70"
runat="server" ReadOnly="True"></asp:TextBox>
<asp:TextBox ID="tbTo" Font-Names="Arial" Font-Size="8pt" Width="70"
runat="server" ReadOnly="True"></asp:TextBox>

sever side code
if (tbFrom.Text.Trim() != "")
{
//after i assign the value the text value is NULL
}

but i can see the value in text box
Mr.
I've one combobox just above to the txtFromDate and txtToDate, in this combobox I've some values like
Current Month
Last Month
Current Year
Last Year
Within Duration
I am changing txtFromDate and txtToDate text depending on the above selection, For example on selecting Current Year I am putting 01/01/2011 and 01/12/2011 in txtFromDate and txtToDate,
i am doing this in a ajax update panel
the problem is this when the page start this jquery calender is showing fine on both text boxes but when i change values inside these textboxes by selecting some item from combobox (which calling a code behind function through ajax) after that when i again click any of the textbox the jquery calender is not showing off,

any idea what i have to do?
Very Nice
Hey bro.....very nice.....i like it...
Thanx
ASP.Net Datepicker
hi Friend,

there is name as Free Asp.net jquery datepicker available online.

its jquery datepicker asp.net user control that you can use in your project.

please check following link to view demo and download.

http://worldcode.brinkster.net/Dot_Net_Tools/Calender.aspx
try datepicker
http://datepicker.org.ru/
thanks
simple and effective
best tutorials...........
thanks.......................
On selecting a date from Date Picker in the text box, the grid view should appear.
Hey please anyone help me out for this..
master page
it doesn't work with master page
RE:Need Help
Its high time to upgrade your browser...You will be out of date if you still use IE 6.0
Need Help
It's working very very slowly in IE6..Is there any solution for that..
Nice
this is a good article
Thank's man
Need help
HI,

I am new to calendar control in asp.net
I am confuse where to put these function

I have created a page with text box and image button
I have also created one page called as DatePicker.aspx along with DatePicker.aspx.cs


Please help to put those code at proper position
jquery calendar ASP.net
I am having hard times to integrate jquery calendar in asp.net Listview/Gridview/detailsview in edit/insert mode. Can somebody please help me.

http://www.southdesk.com
Thanks
Hi, its fantastic, but I need date in this format (DD/MM/YY). Can You help me?thanks.
Re: Master Pages and JQuery
Use
$('#<%=txtDate.ClientID %>').datepicker();

for ASP.Net in general, even when not using master pages.

V cool nevertheless!
datepicker
It will be more useful if write codes in c#
nice
nice but asp.net sounds complicated.
h
very new to it please be little brief
RE:Master Pages
Please make sure you are refrencing the client id of the control correctly when using Master Pages.

$('#<%=txtDate.ClientID %>').datepicker();
Master Pages
It doesn't work with masterpages.
Thank You
Thanks Simple yet effective
convert to VB simply and worked a treat
Very good article !
Hi Satheesh,
Your .Net code for date-picker is very good and simple. I used it in my application and it's working fine.

Thank you so much. You don't know how much you helped me.
Validation?
One thing you have not mentioned is whether the jQuery datepicker will trigger any validators on the page. I have seen instances where, when you use javascript to fill a textbox, the validators on the textbox do not fire (just on client side of course - you should always check on server-side as well).
AJAX
Great Article. Simple ans sweets example
thanks
This is good...
i like it