Click here to Skip to main content
Click here to Skip to main content

ASP.NET DatePicker User Control (Hijri / Gregorian) shows month and year as dropdowns

, 6 May 2013
Rate this:
Please Sign up or sign in to vote.
ASP.NET Date Selector User Control based on calendar control.

You can try live demo here.

Introduction

I am developing an application that uses the date picker for date fields like date of birth and expiry date. Some fields should be entered in Hijri or Gregorian because here in Saudi Arabia the official calendar is the Hijri Calendar and many people know their dates in Hijri only. So I need a date picker control to allow the user to choose the calendar (Hijri or Gregorian) and finally fill both dates in textboxes.

I was looking for an AJAX or jQuery date picker that supports Hijri and Gregorian. Also show month and year as drop downs instead of the static month/year header to facilitate navigation through a large time frame. Unfortunately I did not find any control supporting Hijri, the AJAX one here has a bug in Hijri year navigation.

Introduction to the Islamic (Hijri) Calendar

The Islamic calendar, Muslim calendar, or Hijri calendar (AH) is a lunar calendar consisting of 12 months in a year of 354 or 355 days. Being a purely lunar calendar, it is not synchronized with the seasons. With an annual drift of 10 or 11 days, the seasonal relation repeats about every 33 Islamic years (every 32 solar years).

It is used to date events in many Muslim countries (concurrently with the Gregorian calendar), and is used by Muslims everywhere to determine the proper days on which to observe the annual fast (Ramadan), to attend Hajj, and to celebrate other Islamic holidays and festivals.

The first year was the Islamic year beginning in AD 622 during which the emigration of prophet Muhammad, peace be upon him, from Mecca to Medina, known as the Hijra, occurred. Each numbered year is designated either H for Hijra or AH for the Latin anno Hegirae (in the year of the Hijra) [3] hence Muslims typically call their calendar the Hijri calendar.

The current Islamic year is 1434 AH. In the Gregorian calendar 1434 AH runs from approximately 14 November 2012 to 4 November 2013.

Using the Code 

Simply drag and drop the user control into your ASPX page, add ScriptManger to your ASPX page, and calendar image to your solution. More information about including the user control in an ASP.NET web Page.

User Control Properties

The control exposes six properties: DefaultCalendarCulture, SelectedCalendareDate, getHijriDateText, getGregorianDateText, MinYearCountFromNow and MaxYearCountFromNow that can be used in the hosting page.

  1. DefaultCalendarCulture

  2. Expose default calendar culture and show the little Intellisense box pop up options (Higri, Gregorian).

    Intellisense

    //To set the default Calendar to Hijri 
    <uc1:HijriGregDatePicker ID="HijriGregDatePicker1" 
      runat="server"  DefaultCalendarCulture="Arabic" >
    
    //To set the default Calendar to Gregorian from Source
    <uc1:HijriGregDatePicker ID="HijriGregDatePicker2" 
      runat="server"  DefaultCalendarCulture="English" >
    
    //To set the default Calendar to Hijri from Code
    HijriGregDatePicker1.DefaultCalendarCulture =DatePicker.DefaultCultureOption.Arabic;
    
    //To set the default Calendar to Gregorian from Code
    HijriGregDatePicker1.DefaultCalendarCulture =DatePicker.DefaultCultureOption.English;
    
    //Note that if you have multiple instances from the userconrtrol
    //you have to give all of instances the same default culture
    //otherwise you will got inconvenient behaviour
  3. SelectedCalendareDate

  4. You can get the Hijri selected date:

    HijriGregDatePicker1.SelectedCalendareDate.ToString(strDateFormat, 
       new CultureInfo("ar-SA").DateTimeFormat); 

    You can get the Gregorian selected date:

    HijriGregDatePicker1.SelectedCalendareDate.ToString(strDateFormat, 
       new CultureInfo("en-US").DateTimeFormat);

    You can set the date from the database:

    if (!IsPostBack)
    {
        DataView dvDataView = (DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty);
        HijriGregDatePicker1.SelectedCalendareDate = (DateTime)dvDataView[0][0];   
    }
  5. getHijriDateText

  6. To get the Hijri date from the Hijri text box:

    string strHijri = HijriGregDatePicker1.getHijriDateText; 
  7. getGregorianDateText

  8. To get the Gregorian date from the Gregorian text box:

    string strGreg = HijriGregDatePicker1.getGregorianDateText;
  9. MinYearCountFromNow

  10. To set the minimum year allowed to be selected in the year dropdwon list:

    //To set the minimum year to 2003
    HijriGregDatePicker1.MinYearCountFromNow = -10;
  11. MaxYearCountFromNow

  12. To set the maximum year allowed to be selected on year dropdwon list:

    //to set the maximum year to 2023
    HijriGregDatePicker1.MaxYearCountFromNow = 10;

The Solution

I depended on the ASPX calendar control to develop this solution and the main problem was that the calendar control loaded according to the page culture and there was no way to change the calendar culture without changing the page culture.

I created a usercontrol for this matter to behave like a date picker, toggling between cultures using a dropdown list that changed the page culture. Also I put this user control inside an UpdatePanel to partially update the calendar without affecting the current page.

In other words I can say since we cannot set two different cultures in a single page, this solution is a workaround to allow the user to use multiple calendars in the same page.

Multiple Instances from the User Control in the Same Page

It was a big challenge for me to allow multiple instances. Because I have to manage the post back and culture changing for all instances. For example if the post back is triggered from the culture dropdown list, year dropdown list, or month dropdown list, the calendar div will stay visible but if triggered by other controls the calendar div status will be changed to hidden.

//To get the potpack control name
private string getPostBackControlName()
{
    Control control = null;
    //first we will check the "__EVENTTARGET" because if post back made by the controls
    //which used "_doPostBack" function also available in Request.Form collection.
    string ctrlname = Page.Request.Params["__EVENTTARGET"];
    if (ctrlname != null && ctrlname != String.Empty)
    {
        control = Page.FindControl(ctrlname);
    }

    if (control == null)
    {
        return string.Empty;
    }
    else
    {
        //to catch the control name in case of multiple instances
        return control.UniqueID;
    }
}

User Control JavaScript

The JavaScript for this user control is very simple as below:

  1. Show/hide the calendar date picker
  2. //To Show hide the div when user click on calendar image or any date text boxes
    <script type="text/javascript">
        function showHide(div) {
            if (document.getElementById(div).style.display == "none") {
                document.getElementById(div).style.display = "block";
            }
            else { document.getElementById(div).style.display = "none"; }
        }
    </script>
  3. Hiding the date picker when the user clickd on any place outside date picker box
  4. //to hide the date picker when user click outside the date picker box
    <script type="text/javascript">
    document.onclick = function (e) {
        e = e || event
        var target = e.target || e.srcElement
        var box = document.getElementById('<% =this.whole_calendar.ClientID %>')
        var imgCal = document.getElementById('<% =this.imgCalendar.ClientID %>')
        var txtHijri = document.getElementById('<% =this.txtHijri.ClientID %>')
        var txtGreg = document.getElementById('<% =this.txtGreg.ClientID %>')
        do {
            if (box == target | imgCal == target | txtHijri == target | txtGreg == target) {
                // Click occured inside the box, do nothing.
                return
            }
            target = target.parentNode
        }
        while (target)
        // Click was outside the box, hide it.
        box.style.display = "none"
    }
    </script>

Points of Interest

Note that when you change the date picker culture (Hijri to Gregorian or vice versa), you change the page culture also. Therefore if you are using resource files (localization) I suggest you save the page culture in the hidden field when the page loads and retrieve it back when submitting, as below:

protected void Page_Load(object sender, EventArgs e)
{
    hidCulture.Value = CultureInfo.CurrentCulture.ToString();
}

protected void btnSubmit_Click(object sender, EventArgs e)
{
    System.Globalization.CultureInfo culture = 
            System.Globalization.CultureInfo.CreateSpecificCulture(hidCulture.Value);
    System.Threading.Thread.CurrentThread.CurrentCulture = culture;
    System.Threading.Thread.CurrentThread.CurrentUICulture = culture;
}

Limitation

Note that you if you want to use the calendar for single culture only, then you can disable the dropdown list for changing culture. But if you have many cultures in your application, you cannot enforce the user to choose a date in a specific culture only, because the other user control instances will be affected and any change in page culture will affect the calendar.

Browser Compatibility

This control has been tested on Firefox 18, Internet Explorer 10, and Chrome 25, Safari 5.

Finally

I tried my best to make this user control free of bugs. Any comments, ideas, and suggestions are most welcome for further improvement in this user control.

References

History

  • Version 1.0: 31/03/2013.

License

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

About the Author

Yahya Mohammed Ammouri
Technical Lead Netways Arabia
Saudi Arabia Saudi Arabia
No Biography provided

Comments and Discussions

 
QuestionHow do i reset this control? PinmemberSangram Nandkhile17-Jul-14 8:37 
QuestionCAN YOU POST THE PROJECT TO GENERATE THE DLL CALENDARY? Pinmembermandala863-Jun-14 2:58 
AnswerRe: CAN YOU POST THE PROJECT TO GENERATE THE DLL CALENDARY? PinpremiumYahya Mohammed Ammouri3-Jun-14 4:49 
QuestionSaving In Hijri PinprofessionalMansoor_Ahmed10-Feb-14 20:08 
AnswerRe: Saving In Hijri PinmemberYahya Mohammed Ammouri11-Feb-14 7:46 
QuestionAdding Hijri/Gregorian date on MyForm's text box on selecting the day from calender PinmemberAbdul Aziz Majid29-Jan-14 20:27 
AnswerRe: Adding Hijri/Gregorian date on MyForm's text box on selecting the day from calender PinmemberYahya Mohammed Ammouri29-Jan-14 21:13 
GeneralRe: Adding Hijri/Gregorian date on MyForm's text box on selecting the day from calender PinmemberAbdul Aziz Majid29-Jan-14 21:53 
QuestionRequire Help PinmemberMember 846316827-Jan-14 0:18 
AnswerRe: Require Help PinmemberYahya Mohammed Ammouri27-Jan-14 3:25 
AnswerRe: Require Help PinprofessionalMansoor_Ahmed27-Jan-14 18:59 
QuestionI NEED CODE IN VB.NET PinmemberMember 270341515-Jan-14 20:15 
AnswerRe: I NEED CODE IN VB.NET PinmemberYahya Mohammed Ammouri15-Jan-14 21:40 
GeneralThank you PinmemberMember 83615454-Dec-13 20:59 
QuestionException (StartIndex cannot be less than zero.) [modified] Pinmemberelbanna22-Jun-13 20:22 
BugProblem when selecting year PinmemberJamsheed Rahman15-May-13 19:51 
GeneralRe: Problem when selecting year PinpremiumYahya Mohammed Ammouri2-Apr-14 3:19 
GeneralMy vote of 5 Pinmemberahmed rageeb14-May-13 9:00 
GeneralMy vote of 5 PinmemberMihai MOGA10-May-13 18:28 
GeneralRe: My vote of 5 PinmemberYahya Mohammed Ammouri11-May-13 22:15 
QuestionGreat !! PinprofessionalMohamedKamalPharm6-May-13 16:54 
Questionanother question PinmemberM.Saied27-Apr-13 22:06 
AnswerRe: another question PinmemberYahya Mohammed Ammouri27-Apr-13 22:19 
GeneralRe: another question PinmemberM.Saied27-Apr-13 22:49 
GeneralRe: another question PinmemberYahya Mohammed Ammouri27-Apr-13 23:30 
Questionnicely done [modified] PinmemberM.Saied23-Apr-13 21:56 
AnswerRe: nicely done PinmemberYahya Mohammed Ammouri24-Apr-13 0:26 
GeneralRe: nicely done PinmemberM.Saied24-Apr-13 0:59 
GeneralRe: nicely done PinmemberYahya Mohammed Ammouri24-Apr-13 1:45 
GeneralRe: nicely done PinmemberM.Saied24-Apr-13 3:01 
GeneralRe: nicely done PinmemberYahya Mohammed Ammouri24-Apr-13 3:37 
GeneralRe: nicely done PinmemberM.Saied24-Apr-13 4:56 
QuestionNeed Help. I'm new to this PinmemberMember 795714210-Apr-13 12:10 
AnswerRe: Need Help. I'm new to this [modified] PinmemberYahya Mohammed Ammouri13-Apr-13 21:25 
GeneralRe: Need Help. I'm new to this PinmemberMember 795714216-Apr-13 6:28 
GeneralRe: Need Help. I'm new to this PinmemberYahya Mohammed Ammouri16-Apr-13 19:32 
GeneralMy vote of 5 Pinmemberthe algabban9-Apr-13 19:30 
GeneralRe: My vote of 5 PinmemberYahya Mohammed Ammouri15-Apr-13 19:57 
QuestionCalendar control in HTML 5 PinmemberPham Dinh Truong8-Apr-13 3:51 
AnswerRe: Calendar control in HTML 5 PinmemberYahya Mohammed Ammouri8-Apr-13 22:38 
GeneralMy vote of 5 PinmemberАslam Iqbal3-Apr-13 2:41 
GeneralRe: My vote of 5 PinmemberYahya Mohammed Ammouri8-Apr-13 22:38 

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 | Mobile
Web03 | 2.8.140721.1 | Last Updated 6 May 2013
Article Copyright 2013 by Yahya Mohammed Ammouri
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid