Click here to Skip to main content
11,505,486 members (42,092 online)
Click here to Skip to main content

Date Picker User Control

, 2 Dec 2011 CPOL 188.7K 11.6K 100
Rate this:
Please Sign up or sign in to vote.
A date picker user control in ASP.NET (C#, VS2010)

Introduction

This is a simple date-picker control that comes as an ASP.NET custom control. The user can either enter a date into a textbox or click on an icon which opens a pop-up calendar. JavaScript is used to display the pop-up calendar. The control can easily be integrated in your own ASP.NET websites by simply referencing the Assembly and drag'n'drop the control from the toolbox onto your web form.

Background

This control is originally based on another CodeProject article. In my first release back in 2007, I overworked the control so it compiles with VS2005 and works with the latest versions of Firefox and Internet Explorer. I fixed some JavaScript errors and added better design time support and data-binding. In the first release, the date-picker control was a so called User Control (.ascx file) which you had to include in your ASP.NET web project, together with some JavaScript, CSS and image files.

Now, in 2011, I publish a new major release. This time, the date-picker is implemented as a Custom Control. This means that it comes as an Assembly (DLL file) which you can simply reference from your ASP.NET web application and then drag'n'drop from the toolbox onto your web form. All required resources like JavaScript, CSS or images files are included in the single DLL and loaded as web resources.

Using the Code

To use the date picker control in your own web project, simply add a reference to the DatePickerControl.dll which you can download from the link at the top of this page.

To manually add a datepicker instance to an .aspx form, add the following code:

<%@ Register assembly="DatePickerControl" 
namespace="DatePickerControl" tagprefix="cc1" %>

<cc1:DatePicker ID="DatePicker1" runat="server" />

If you want to have the datepicker control into your toolbox, you need to manually add it. To do so, right click into the toolbox and select "Choose items..." from the context menu. Then click on the "Browse..." button and select the DatePickerControl.dll. A new control will appear in your toolbox which you can drag'n'drop to any web form:

What I Have Learned

During the development of this custom control, I learnt a lot of things about custom control development. There are a few points of interest I like to share.

Web Resources

My control is using additional resources like images, CSS and JavaScript files. Because I wanted everything to be included into a single DLL, I added all the required files as "embedded resources". Make sure that the "Build Action" in the properties for all the resource files is set to "Embedded Resource". Then you need to edit the "AssemblyInfo.cs" file and add a "WebResource" declaration for each file that you want to access via an auto-generated URL:

[assembly: System.Web.UI.WebResource("DatePickerControl.Resources.popcalendar.css", 
	"text/css")]
[assembly: System.Web.UI.WebResource("DatePickerControl.Resources.popcalendar.js", 
	"text/javascript", PerformSubstitution = true)]
[assembly: System.Web.UI.WebResource("DatePickerControl.Resources.calendar.gif", 
	"image/gif")]    

To get the URL to one of the resource files, use the "Page.ClientScript.GetWebResourceUrl" method. For example, to include the JavaScript file, I use the following code:

 Page.ClientScript.RegisterClientScriptInclude(this.GetType(), "js",
    Page.ClientScript.GetWebResourceUrl(this.GetType(), 
	"DatePickerControl.Resources.popcalendar.js"));    

It is very important to add the assembly name to the string passed to the "Page.ClientScript.GetWebResourceUrl" method!

BTW: The URL returned by the "Page.ClientScript.GetWebResourceUrl" method looks something like this:

 /WebResource.axd?d=VKJPowiRQrngH4t6...wQza83c1&t=634583660937215237    

Property Default Values

I also wanted some design time support, for example properties of my control should have a default value. And I wanted the default value to appear as default (=not bold) in the property grid, whereas non-default values should appear as non-default (=bold):

In case of String, Int or Enum properties, this is pretty easy and can be achieved by adding some extra attributes to the property declaration:

[Category("Appearance")]
[Description("Day to start week with.")]
[Browsable(true)]
[DefaultValue(Weekday.Monday)]
public Weekday StartWeekWithDay
{

But for the DateFormat property, I wanted the default to be culture dependent: On a European Windows installation, the default date format should be dd.MM.yyyy, whereas on U.S. system, the default should be MM/dd/yyyy. How could this be done? Fortunately, we can also write our own code to set the default value of a property. To do so, we have to add two private methods for the property. These methods must be named Reset...() and ShouldSerialize...(), where the ... is replaced with the name of the property. Let's look at the DateFormat property:

public string DateFormat
{
    get { return dateFormat; }
    set { dateFormat = value; }
}

private void ResetDateFormat()
{
    DateFormat = CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern;
}

private bool ShouldSerializeDateFormat()
{
    return (!DateFormat.Equals
	(CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern));
}

The ResetDateFormat() method just sets the property to whatever should be your default value. The ShouldSerializeDateFormat() method returns a boolean that is used to determine whether the property value needs to be serialized. This is only the case if it is different from its default value.

HTML Design Time

In the designer, the date picker control is displayed quite different than on a real web page. Unfortunately, I could not figure out a way to display the calendar image from the embedded resources during design-time:

However, I learned that you can control the HTML that is used to render a control during design-time by adding a class inherited from "ControlDesigner" to your control DLL. The class must be named the same as the control but with a "Designer" suffix. For the "DatePicker" control, this class would be named "DatePickerDesigner". Within this class, the "GetDesignTimeHtml()" method can be overridden to return a custom HTML string.

CSS and JavaScript Include

If you place the date picker control onto a web form, it should automatically include the required CSS and JavaScript files. However if you place two or more date picker controls on the same page, these files should only be included once. To include a JavaScript file, the "RegisterClientScriptInclude" method can be used:

Page.ClientScript.RegisterClientScriptInclude
	(this.GetType(), "js", "your_javascript.js");

This method automatically ensures that the same JavaScript is only included once, even if the method is called multiple times from multiple control instances.

Including a CSS file is a bit more complicated. As we all know, CSS files should be included within the <head></head> tags of your web page. The controls within the page header can be accessed via the "Page.Header" property. A link to a CSS file can be added using the following code:

LiteralControl include = new LiteralControl
    ("<link href='your_css.css' rel='stylesheet' type='text/css' />");
Page.Header.Controls.Add(include);  

But how can we make sure that the same CSS is only included once if multiple date picker controls are added to the same page? We can make use of the "RegisterClientScriptInclude" method mentioned before. There is another method "Page.ClientScript.IsClientScriptIncludeRegistered" that we can use to query whether a JavaScript has already been included or not. So we can simply include the CSS only if the JavaScript has not already been included.

History

  • December 2007 -- Original version posted
  • April 2009 -- Updated (many bugfixes, moved to VS2008, examples added)
  • August 2010 -- Updated source code and demo
  • December 2011 -- Rewritten as a custom control, everything compiled into one DLL, moved to VS2010, more examples added

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Simon B.
Software Developer Sevitec AG
Switzerland Switzerland
No Biography provided

Comments and Discussions

 
QuestionCan't reference the DatePicker if template field Pin
Member 1151984316-Mar-15 10:28
memberMember 1151984316-Mar-15 10:28 
Questiona question about this control in Stackoverflow Pin
Mohamad Shawkey31-Jul-14 2:58
memberMohamad Shawkey31-Jul-14 2:58 
QuestionDatePicker with Required Field Validator and allow type property Pin
Mohamad Shawkey30-Jul-14 6:30
memberMohamad Shawkey30-Jul-14 6:30 
QuestionPlease add as a Nuget package Pin
yodamon22-Jul-14 6:00
memberyodamon22-Jul-14 6:00 
QuestionClear the field!!! urgent Pin
perlita2426-May-14 4:55
memberperlita2426-May-14 4:55 
Questionhow to pick value from datepicker Pin
Member 1060800618-Feb-14 21:42
memberMember 1060800618-Feb-14 21:42 
QuestionRe: how to pick value from datepicker Pin
Member 1056592528-May-15 1:57
memberMember 1056592528-May-15 1:57 
QuestionDatepicker css Pin
jamesonkeju9-Feb-14 22:50
memberjamesonkeju9-Feb-14 22:50 
NewsDTPicker User Control Pin
gustavoz17-Oct-13 4:13
membergustavoz17-Oct-13 4:13 
QuestionDate picker control not working on Chrome 29 Pin
Mr Nicolaides4-Sep-13 2:27
memberMr Nicolaides4-Sep-13 2:27 
QuestionHow can I desactivate the textbox?? Pin
Member 953345519-Jul-13 23:36
memberMember 953345519-Jul-13 23:36 
QuestionHow to assign date to the control Pin
Thaupeek11-Jun-13 3:06
memberThaupeek11-Jun-13 3:06 
AnswerRe: How to assign date to the control Pin
rawl20004-Aug-14 9:55
memberrawl20004-Aug-14 9:55 
QuestionMarch 2013 is showing only 30days! Pin
dasarathM9-Apr-13 9:08
memberdasarathM9-Apr-13 9:08 
QuestionMultiple Controls All Update First One - StaticID Pin
Toyist2-Mar-13 11:05
memberToyist2-Mar-13 11:05 
QuestionReload Pin
ApachieKam17-Jan-13 6:05
memberApachieKam17-Jan-13 6:05 
GeneralMy vote of 5 Pin
ashutosh k. shukla9-Dec-12 1:07
memberashutosh k. shukla9-Dec-12 1:07 
QuestionExcellent job Pin
bruno leclerc18-Oct-12 22:33
memberbruno leclerc18-Oct-12 22:33 
Generalthanks Simon!!! Pin
hugetienne12-Oct-12 1:34
memberhugetienne12-Oct-12 1:34 
Questioncurrent month text and year text not showing Pin
aneesh00730-Aug-12 5:35
memberaneesh00730-Aug-12 5:35 
GeneralObject required - Error [modified] Pin
Member 373478311-Jul-12 5:31
memberMember 373478311-Jul-12 5:31 
Questiononly working in chrome?? Pin
Taysseer Kadri20-Jun-12 21:09
memberTaysseer Kadri20-Jun-12 21:09 
AnswerRe: only working in chrome?? Pin
Simon B.22-Aug-12 11:39
memberSimon B.22-Aug-12 11:39 
QuestionAbout ur datapicker Pin
junetanweiting20-Jun-12 3:28
memberjunetanweiting20-Jun-12 3:28 
QuestionPopup value for long date formats Pin
Matt220225-Apr-12 23:38
memberMatt220225-Apr-12 23:38 
AnswerRe: Popup value for long date formats Pin
Simon B.22-Aug-12 11:38
memberSimon B.22-Aug-12 11:38 
QuestionVery Nice! Pin
MrReed4-Apr-12 19:59
memberMrReed4-Apr-12 19:59 
GeneralMy vote of 5 Pin
cars9529-Mar-12 10:10
membercars9529-Mar-12 10:10 
QuestionTranslate language in datepicker user control Pin
duonglg19-Mar-12 17:53
memberduonglg19-Mar-12 17:53 
Questionthanks alot Pin
sanamshaikh2-Mar-12 1:38
membersanamshaikh2-Mar-12 1:38 
NewsCompletely new version released! [modified] Pin
Simon B.2-Dec-11 23:32
memberSimon B.2-Dec-11 23:32 
BugRe: Completely new version released! Pin
Larry Whipple9-Dec-11 5:53
memberLarry Whipple9-Dec-11 5:53 
AnswerRe: Completely new version released! Pin
Simon B.9-Dec-11 23:28
memberSimon B.9-Dec-11 23:28 
GeneralMy vote of 5 Pin
Arrigons1-Apr-11 0:35
memberArrigons1-Apr-11 0:35 
GeneralPost back event Pin
Savun15-Oct-10 0:22
memberSavun15-Oct-10 0:22 
GeneralAttach .css file automatically Pin
Savun15-Oct-10 0:16
memberSavun15-Oct-10 0:16 
GeneralThanks a Lot! Pin
rmcomics14-Oct-10 7:13
memberrmcomics14-Oct-10 7:13 
QuestionThanks (dll library?) Pin
emtz_o18-Aug-10 6:51
memberemtz_o18-Aug-10 6:51 
NewsNew sources released (v3) Pin
Simon B.17-Aug-10 11:11
memberSimon B.17-Aug-10 11:11 
GeneralDefault Date Format Pin
crb900017-Aug-10 9:18
membercrb900017-Aug-10 9:18 
AnswerRe: Default Date Format Pin
Simon B.17-Aug-10 11:08
memberSimon B.17-Aug-10 11:08 
GeneralDynamically added your control to web page Pin
Gopal Sharma IBM13-Aug-10 1:44
memberGopal Sharma IBM13-Aug-10 1:44 
GeneralRe: Dynamically added your control to web page Pin
Simon B.15-Aug-10 4:33
memberSimon B.15-Aug-10 4:33 
GeneralMy vote of 5 Pin
Member 397940427-Jul-10 0:39
memberMember 397940427-Jul-10 0:39 
AnswerNice DatePicker Pin
Member 420460526-Jul-10 19:50
memberMember 420460526-Jul-10 19:50 
GeneralRe: Nice DatePicker Pin
Simon B.15-Aug-10 4:35
memberSimon B.15-Aug-10 4:35 
AnswerJavaScript-VB error fix for date formats containing "mmm" .. (don't know about C#) Pin
olaforest12-Jun-10 20:48
memberolaforest12-Jun-10 20:48 
NewsRe: JavaScript-VB error fix for date formats containing "mmm" .. (don't know about C#) Pin
Simon B.15-Aug-10 5:40
memberSimon B.15-Aug-10 5:40 
GeneralThanks Pin
efero10-May-10 21:05
memberefero10-May-10 21:05 
Generalthanks Pin
meghajj10-Apr-10 22:21
membermeghajj10-Apr-10 22:21 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150520.1 | Last Updated 2 Dec 2011
Article Copyright 2007 by Simon B.
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid