Click here to Skip to main content
15,896,441 members
Articles / Web Development / ASP.NET

Date Picker User Control

Rate me:
Please Sign up or sign in to vote.
4.66/5 (43 votes)
2 Dec 2011CPOL6 min read 375.3K   18.2K   99  
A date picker user control in ASP.NET (C#, VS2010)
/*
 * DateTimePicker
 * 
 * Copyright (c) 2009..10 by Simon Baer.
 * Licensed unter the Code Project Open License (CPOL).
 * 
 * v3: Support for more date patterns (MMM, MMMM, ddd, dddd)
 */

using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
using System.Globalization;
using System.Text;

[ValidationPropertyAttribute("CalendarDateString")]
public partial class Calendar_Date : System.Web.UI.UserControl
{
	public enum Weekday
	{
		Sunday = 0,
		Monday = 1
	}

    // date format used by the calendar control
	private string dateFormat = CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern;

	// whether the control is enabled
    private bool enabled = true;

	// day to start week with
	private int startAt = (int)Weekday.Monday;

	/// <summary>
	/// Register JavaScripts.
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
    protected void Page_Load(object sender, EventArgs e)
    {
		if (!Page.ClientScript.IsClientScriptIncludeRegistered("datepickerctrl"))
		{
			Page.ClientScript.RegisterClientScriptInclude("datepickerctrl", "cal/popcalendar.js");
			Page.ClientScript.RegisterStartupScript(this.GetType(), "dtpck_start", "initPicker('" + ResolveUrl("cal") + "/');", true);

			// localized month names
			StringBuilder sb = new StringBuilder();
			for (int i = 0; i < 12; i++)
			{
				Page.ClientScript.RegisterArrayDeclaration("monthName", "\"" + CultureInfo.CurrentCulture.DateTimeFormat.MonthNames[i] + "\"");
                Page.ClientScript.RegisterArrayDeclaration("monthAbbr", "\"" + CultureInfo.CurrentCulture.DateTimeFormat.AbbreviatedMonthNames[i] + "\"");
			}

			// localized day abbreviations
			sb = new StringBuilder();
			for (int i = 0; i < 7; i++)
			{
				Page.ClientScript.RegisterArrayDeclaration("dayName", "\"" + CultureInfo.CurrentCulture.DateTimeFormat.AbbreviatedDayNames[i] + "\"");
                Page.ClientScript.RegisterArrayDeclaration("dayNameLong", "\"" + CultureInfo.CurrentCulture.DateTimeFormat.DayNames[i] + "\"");
			}
		}
    }

	/// <summary>
	/// Gets or sets the CSS class to apply to the textbox.
	/// </summary>
    [Category("Appearance")]
    [Description("CSS class name applied to the text box.")]
    [Browsable(true)]
    public string TextCssClass
    {
        get { return txt_Date.CssClass; }
        set { txt_Date.CssClass = value; }
    }

	/// <summary>
	/// Gets or sets the day to start the week with.
	/// </summary>
	[Category("Appearance")]
	[Description("Day to start week with.")]
	[Browsable(true)]
	[DefaultValue(Weekday.Monday)]
	public Weekday StartWeekWithDay
	{
		get { return (Weekday)startAt; }
		set { startAt = (int)value; }
	}

    /// <summary>
    /// Gets or sets the day to start the week with.
    /// </summary>
    [Category("Appearance")]
    [Description("Width of date text field.")]
    [Browsable(true)]
    [DefaultValue(70)]
    public int DateWidth
    {
        get { return (int)txt_Date.Width.Value; }
        set { txt_Date.Width = Unit.Pixel(value); }
    }

    /// <summary>
    /// Gets or sets the content of the textbox which represents a date.
    /// </summary>
	[Category("Appearance")]
    [Bindable(true, BindingDirection.TwoWay)]
    [Browsable(true)]
    public string CalendarDateString
    {
        get { return txt_Date.Text; }
        set
        {
            txt_Date.Text = value;
            DateTime date;
			if (DateTime.TryParseExact(value, dateFormat, null, System.Globalization.DateTimeStyles.None, out date))
            {
                if (date.Date == DateTime.MaxValue.Date)
                {
                    txt_Date.Text = "";
                }
            }
        }
    }

    /// <summary>
    /// Gets or sets a DateTime representation of the currently selected date.
    /// </summary>
	[Category("Appearance")]
	[Bindable(true, BindingDirection.TwoWay)]
    [Browsable(true)]
    public DateTime CalendarDate
    {
        get
        {
            DateTime date;
            if (DateTime.TryParseExact(txt_Date.Text, dateFormat, null, System.Globalization.DateTimeStyles.None, out date))
            {
                return date;
            }
            return DateTime.MaxValue;
        }
        set { txt_Date.Text = value.ToString(dateFormat); }
    }

    /// <summary>
    /// Gets a flag indicating whether a valid date has been selected.
    /// </summary>
    public bool IsValidDate
    {
        get
        {
            DateTime date;
			return DateTime.TryParseExact(txt_Date.Text, dateFormat, null, System.Globalization.DateTimeStyles.None, out date);
        }
    }

    /// <summary>
    /// Gets or sets a value indicating whether the date picker control is enabled.
    /// </summary>
	[Category("Behavior")]
	[Bindable(true, BindingDirection.TwoWay)]
    [Browsable(true)]
	[DefaultValue(true)]
    public bool Enabled
    {
        get { return enabled; }
        set { enabled = value; }
    }

	/// <summary>
	/// Gets or sets the date format to use, e.g. "dd.MM.yyyy" or "MM/dd/yyyy".
	/// </summary>
	[Category("Appearance")]
	[Description("Date format, e.g. 'dd.MM.yyyy' or 'MM/dd/yyyy'.")]
	[Browsable(true)]
	public string DateFormat
	{
		get { return dateFormat.Replace("\\/", "/"); }
		set { dateFormat = value.Replace("/", "\\/"); }
	}

    /// <summary>
    /// Set some properties of the child controls before rendering.
    /// </summary>
    /// <param name="e"></param>
    protected override void OnPreRender(EventArgs e)
    {
        txt_Date.Enabled = enabled;
        imgCalendar.ImageUrl = enabled ? "cal/calendar.gif" : "cal/calendar_disabled.gif";

        if (enabled)
        {
			string scriptStr = "javascript:return popUpCalendar(this, document.getElementById('" + txt_Date.ClientID + @"'), '" + DateFormat + "', " + startAt.ToString() + ")";
            imgCalendar.Attributes.Add("onclick", scriptStr);
        }

        base.OnPreRender(e);
    }

    /// <summary>
    /// Save custom control properties in viewstate.
    /// </summary>
    /// <returns></returns>
    protected override object SaveViewState()
    {
        object[] allStates = new object[2];
        allStates[0] = base.SaveViewState();
        allStates[1] = enabled;
        return allStates;
    }

    /// <summary>
    /// Load custom control properties from viewstate.
    /// </summary>
    /// <param name="savedState"></param>
    protected override void LoadViewState(object savedState)
    {
        if (savedState != null)
        {
            // Load State from the array of objects that was saved at SavedViewState
            object[] myState = (object[])savedState;
            if (myState[0] != null)
            {
                base.LoadViewState(myState[0]);
            }
            if (myState[1] != null)
            {
                enabled = (bool)myState[1];
            }
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

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


Written By
Software Developer Sevitec Informatik AG
Switzerland Switzerland
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions