Thursday, September 8, 2011

Simple ASP.net Time Picker Composite Server Control

Today i will introduce commonly used server control for ASP.net, let us describe the control in details.

This control support localization for all possible value you need to localize such as
  1. HoursText
  2. MinutesText
  3. AMText
  4. PMText
  5. LayoutDirection
  6. TextAlign
Available properties in the control
  1. AMPM: provide option if user need time control render as AP-PM mode or not
  2. IsRequired: provide option if user need to make the control required or not
  3. ValidationGroup: option to make user provide "ValidationGroup" sub-controls
  4. DropDownListCssClass: option to provide "CssClass" for Drop Down Lists
  5. Time: "The Default Property" get or set the time value for the control the return value is string and the format depends on the "AMPM" property
  6. ShortTimeString: get the 24 hour-format time as string "hh:mm" as "23:30"
  7. LongTimeString: get the 12 hour-format time as string "hh:mmtt" as "01:30pm" 
  8. HoursText: the first item text for hours drop down list
  9. MinutesText: the first item text for minutes drop down list 
  10. AMText: the AM item text for AMPM drop down list 
  11. PMText: the PM item text for AMPM drop down list  
  12. LayoutDirection: the layout direction for drop down lists "ltr||rtl"
  13. TextAlign: the text align for drop down lists "left||right"
  14. SetCurrentTimeDefault: set the current time as default time selected by time picker
Note: also the control support Arabic numeral automatically

now with the main methods and overrides for rendering the control:


Note: you will find that the class inherits from class "WebControl" and this the main class that will be implemented and also implement the interface called "INamingContainer" and note that you not find any implementation for the interface methods and it used only for creating unique id for newly added control.


Control Collection and Create Child Controls Overrides

 public override ControlCollection Controls  
     {  
       get  
       {  
         EnsureChildControls();  
         return base.Controls;  
       }  
     }  

 protected override void CreateChildControls()  
     {  
       Controls.Clear();  
       #region Drop Down Lists  
       // setting ids  
       ddlHours.ID = "ddlHours";  
       ddlMinutes.ID = "ddlMinutes";  
       ddlAMPM.ID = "ddlAMPM";  
       // text align for drop down lists "left||right"        
       ddlHours.Attributes["style"] = "text-align:" + TextAlign.ToString();  
       ddlMinutes.Attributes["style"] = "text-align:" + TextAlign.ToString();  
       ddlAMPM.Attributes["style"] = "text-align:" + TextAlign.ToString();  
       // check if user provide cssclass for drop down lists  
       if (!string.IsNullOrEmpty(DropDownListCssClass))  
       {  
         ddlHours.CssClass = DropDownListCssClass;  
         ddlMinutes.CssClass = DropDownListCssClass;  
         ddlAMPM.CssClass = DropDownListCssClass;  
       }  
       #endregion  
       #region Required Field Validators  
       // hours RFV  
       rfvHours.Display = ValidatorDisplay.Dynamic;  
       rfvHours.ControlToValidate = "ddlHours";  
       rfvHours.ErrorMessage = "*";  
       rfvHours.InitialValue = "-1";  
       // minutes RFV  
       rfvMinutes.Display = ValidatorDisplay.Dynamic;  
       rfvMinutes.ControlToValidate = "ddlMinutes";  
       rfvMinutes.ErrorMessage = "*";  
       rfvMinutes.InitialValue = "-1";  
       // check if user need this instance required or not  
       if (!IsRequired)  
       {  
         rfvHours.Enabled = false;  
         rfvMinutes.Enabled = false;  
       }  
       else  
         if (!string.IsNullOrEmpty(ValidationGroup))  
         {  
           ddlHours.ValidationGroup = ValidationGroup;  
           rfvHours.ValidationGroup = ValidationGroup;  
           ddlMinutes.ValidationGroup = ValidationGroup;  
           rfvMinutes.ValidationGroup = ValidationGroup;  
         }  
       #endregion  
       #region User Interface  
       Controls.Add(new LiteralControl("<table border=\"0\" cellpadding=\"5\" cellspacing=\"0\" dir=\"" + LayoutDirection.ToString() + "\"><tr><td>"));  
       Controls.Add(ddlHours);  
       Controls.Add(rfvHours);  
       Controls.Add(new LiteralControl("</td><td>"));  
       Controls.Add(ddlMinutes);  
       Controls.Add(rfvMinutes);  
       Controls.Add(new LiteralControl("</td><td>"));  
       Controls.Add(ddlAMPM);  
       Controls.Add(new LiteralControl("</td></tr></table>"));  
       #endregion  
       string _time = string.Empty;  
       // time parts variable for 12 and 24 hour format  
       string[] timeParts = null;  
       if (string.IsNullOrEmpty(Time))  
       {  
         if (SetCurrentTimeDefault)  
         {  
           if (AMPM)  
           {  
             _time = DateTime.Now.ToString("hh:mmtt");  
             // 12hour-format time  
             timeParts = new string[3];  
             timeParts[0] = _time.Split(':')[0].ToString();  
             timeParts[1] = _time.Split(':')[1].Substring(0, 2);  
             timeParts[2] = _time.Split(':')[1].Substring(2, 2);  
           }  
           else  
           {  
             _time = DateTime.Now.ToString("hh:mm");  
             // 24hour-format time  
             timeParts = new string[2];  
             timeParts = _time.Split(':');  
           }  
         }  
         // load time drob down lists  
         LoadTime();  
         if (timeParts != null)  
         {  
           if (AMPM)  
           {  
             ddlHours.SelectedValue = timeParts[0];  
             ddlMinutes.SelectedValue = timeParts[1];  
             ddlAMPM.SelectedValue = timeParts[2];  
           }  
           else  
           {  
             ddlHours.SelectedValue = timeParts[0];  
             ddlMinutes.SelectedValue = timeParts[1];  
           }  
         }  
         // check if user need ampm option or not  
         if (!AMPM)  
           ddlAMPM.Visible = false;  
       }  
     }  




and the main method called LoadTime (to initialize all drop down lists with items)
 private void LoadTime()  
     {  
       try  
       {  
         // fill hours drop down list  
         ddlHours.Items.Clear();  
         if (!AMPM)  
           for (int i = 00; i < 24; i++)  
           {  
             if (HttpContext.Current.Session.LCID == 1025) // arabic  
               ddlHours.Items.Add(new ListItem(i.ToString().Length < 2 ? ConvertToArabicNumeral("0" + i.ToString()) : ConvertToArabicNumeral(i.ToString()), i.ToString().Length < 2 ? "0" + i.ToString() : i.ToString()));  
             else  
               ddlHours.Items.Add(new ListItem(i.ToString().Length < 2 ? "0" + i.ToString() : i.ToString(), i.ToString().Length < 2 ? "0" + i.ToString() : i.ToString()));  
           }  
         else  
           for (int i = 01; i <= 12; i++)  
           {  
             if (HttpContext.Current.Session.LCID == 1025) // arabic  
               ddlHours.Items.Add(new ListItem(i.ToString().Length < 2 ? ConvertToArabicNumeral("0" + i.ToString()) : ConvertToArabicNumeral(i.ToString()), i.ToString().Length < 2 ? "0" + i.ToString() : i.ToString()));  
             else  
               ddlHours.Items.Add(new ListItem(i.ToString().Length < 2 ? "0" + i.ToString() : i.ToString(), i.ToString().Length < 2 ? "0" + i.ToString() : i.ToString()));  
           }  
         // add first item to hours drop down list          
         ddlHours.Items.Insert(0, new ListItem(HoursText, "-1"));  
         // fill minutes drop down list  
         ddlMinutes.Items.Clear();  
         for (int i = 00; i < 60; i++)  
         {  
           if (HttpContext.Current.Session.LCID == 1025) // arabic  
             ddlMinutes.Items.Add(new ListItem(i.ToString().Length < 2 ? ConvertToArabicNumeral("0" + i.ToString()) : ConvertToArabicNumeral(i.ToString()), i.ToString().Length < 2 ? "0" + i.ToString() : i.ToString()));  
           else  
             ddlMinutes.Items.Add(new ListItem(i.ToString().Length < 2 ? "0" + i.ToString() : i.ToString(), i.ToString().Length < 2 ? "0" + i.ToString() : i.ToString()));  
         }  
         // add first item to hours drop down list          
         ddlMinutes.Items.Insert(0, new ListItem(MinutesText, "-1"));  
         #region AMPM DropDownList  
         ddlAMPM.Items.Insert(0, new ListItem(AMText, "AM")); // first item  
         ddlAMPM.Items.Insert(1, new ListItem(PMText, "PM")); // second item  
         #endregion  
       }  
       catch (Exception ex)  
       {  
         throw new Exception(ex.Message);  
       }  
     }  

and the time validation method the support 12 hour-format and 24 hour-format

 private bool ValidateTime(string time, out bool IsAMPM)  
     {  
       IsAMPM = false;  
       bool validTime = false;  
       // validate 12hour-format time string  
       Regex rg12 = new Regex("^([1-9]|1[0-2]|0[1-9]){1}(:[0-5][0-9][aApP][mM]){1}$");  
       if (rg12.IsMatch(time))  
       {  
         validTime = true;  
         IsAMPM = true;  
         return validTime;  
       }  
       // validate 24hour-format time string  
       Regex rg24 = new Regex("^([0-1][0-9]|[2][0-3]):([0-5][0-9])$");  
       if (rg24.IsMatch(time))  
       {  
         validTime = true;  
         return validTime;  
       }  
       return validTime;  
     }  

and the last method for handling Arabic numeral

 // convert from english numeral to arabic numeral  
     protected string ConvertToArabicNumeral(string englishNumber)  
     {  
       string arabicNumebr = englishNumber;  
       try  
       {  
         foreach (char enn in englishNumber)  
         {  
           switch (enn)  
           {  
             case '0':  
               arabicNumebr = arabicNumebr.Replace('0', '٠');  
               break;  
             case '1':  
               arabicNumebr = arabicNumebr.Replace('1', '١');  
               break;  
             case '2':  
               arabicNumebr = arabicNumebr.Replace('2', '٢');  
               break;  
             case '3':  
               arabicNumebr = arabicNumebr.Replace('3', '٣');  
               break;  
             case '4':  
               arabicNumebr = arabicNumebr.Replace('4', '٤');  
               break;  
             case '5':  
               arabicNumebr = arabicNumebr.Replace('5', '٥');  
               break;  
             case '6':  
               arabicNumebr = arabicNumebr.Replace('6', '٦');  
               break;  
             case '7':  
               arabicNumebr = arabicNumebr.Replace('7', '٧');  
               break;  
             case '8':  
               arabicNumebr = arabicNumebr.Replace('8', '٨');  
               break;  
             case '9':  
               arabicNumebr = arabicNumebr.Replace('9', '٩');  
               break;  
           }  
         }  
         return arabicNumebr;  
       }  
       catch  
       {  
         return englishNumber;  
       }  
     }  

now with the registering, using and screen shots of the rendered control

Registering the control through web.config file

 <add tagPrefix="uc1" namespace="CustomControls" assembly="CustomControls" />  

Localized English version (AP-PM 12 hour-format)

 <dev:TimePicker runat="server" ID="tpExpectedReturnTime" AMPM="true" IsRequired="true"  
         ValidationGroup="LeaveForm" TabIndex="10" meta:resourcekey="tpExpectedReturnTimeResource" />  

Localized English Version (24 hour-format)

 <dev:TimePicker runat="server" ID="tpLeaveTime" AMPM="false" IsRequired="true" ValidationGroup="LeaveForm"  
         TabIndex="9" meta:resourcekey="tpLeaveTimeResource" />  

Localized Arabic Sample (AP-PM 12 hour-format)


Note: Newly added method "Reset" that will reset time control (all drop down lists)

Finally i hope for all good luck and i wish that article helpful

Note: you can find the complete source code here that is called "CustomControls.zip"

No comments:

Post a Comment