CodeVerge.Net Beta
Login Idy
Register Password
  Forgot?
Explore    Item Entry    Members   
NEWSGROUP
.NET
Algorithms-Data Structures
Asp.Net
C Plus Plus
CSharp
Database
HTML
Javascript
Linq
Other
Regular Expressions
VB.Net
XML





Zone: > NEWSGROUP > Asp.Net Forum > windows_hosting.hosting_open_forum Tags:
Item Type: NewsGroup Date Entered: 8/12/2005 2:17:58 PM Date Modified: Subscribers: 0 Subscribe Alert
Rate It:
(NR, 0)
XPoints: N/A Replies: 2 Views: 15 Favorited: 0 Favorite
Can Reply:  No Members Can Edit: No Online: Yes
3 Items, 1 Pages 1 |< << Go >> >|
SomeNewTricks2
Asp.Net User
DatePicker control - urgent8/12/2005 2:17:58 PM

0/0

I am working on this DatePicker control which I found on the web, I am trying to customize it to my needs with Client Validation, but it is not working, could you please fix it for me?

this is the datepicket and it works fine.

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Text.RegularExpressions;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace CustomControls
{
    [DefaultProperty("Text"), ValidationProperty("Value")]
    [ToolboxData("<{0}:DatePicker runat=server />")]
    public class DatePicker : CompositeControl, IPostBackDataHandler
    {
        #region Private Fields
        // The dropdownlists to render on the page
        private System.Web.UI.WebControls.DropDownList dayList;
        private System.Web.UI.WebControls.DropDownList yearList;
        private System.Web.UI.WebControls.DropDownList monthList;

        // The arrays used to populate the drop down lists
        // The blanks at the beginning are for a blank item in the list box
        private string[] DayArray = { "", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", 
"16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31" }; private string[] MonthArray = { "", "January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December" }; private string[] YearArray; private static readonly object EventControlChanged = new object(); #endregion #region Properties [ Bindable(true), Category("Misc"), Themeable(true), Description("Sets/Gets the Value of the Date control") ] public string Value { get { string s = (string)ViewState["Value"]; if (s == null) return String.Empty; else return s; } set { this.SetSelected(value); ViewState["Value"] = value; } } // Returns selected day private int SelectedDay { get { if (ViewState["SelectedDay"] == null) return -1; else return (int)ViewState["SelectedDay"]; } set { ViewState["SelectedDay"] = value; } } // Returns selected month private int SelectedMonth { get { if (ViewState["SelectedMonth"] == null) return -1; else return (int)ViewState["SelectedMonth"]; } set { ViewState["SelectedMonth"] = value; } } // Returns selected year private int SelectedYear { get { if (ViewState["SelectedYear"] == null) return -1; else return (int)ViewState["SelectedYear"]; } set { ViewState["SelectedYear"] = value; } } // When this property is true, set the control's value to the current date [ Bindable(true), Category("Misc"), Themeable(true), Description("Says wether to set the initial value to the current day") ] public bool SelectCurrentDate { get { if (ViewState["SelectCurrentDate"] == null) return true; // Default value of true return (bool)ViewState["SelectCurrentDate"]; } set { ViewState["SelectCurrentDate"] = value; bool _setCurrent = value; if (_setCurrent) this.Value = DateTime.Today.ToShortDateString(); } } // Number of years in the past to display [ Bindable(true), Category("Misc"), Themeable(true), Description("Sets/Gets the years to display in the past") ] public int YearsBack { get { if (ViewState["YearBack"] == null) return 10; // Default value of 10 years return (int)ViewState["YearsBack"]; } set { ViewState["YearsBack"] = value; } } // Number of years in the future to display [ Bindable(true), Category("Misc"), Themeable(true), Description("Sets/Gets the years to display in the future") ] public int YearsForward { get { if (ViewState["YearsForward"] == null) return 10; // Default value of 10 years return (int)ViewState["YearsForward"]; } set { ViewState["YearsForward"] = value; } } #endregion #region Event Handler // Remove/Add handler to event public event EventHandler Changed { add { Events.AddHandler(EventControlChanged, value); } remove { Events.RemoveHandler(EventControlChanged, value); } } // Fired when RaisePostDataChangedEvent() protected virtual void OnChanged(EventArgs e) { EventHandler ControlChanged = (EventHandler)Events[EventControlChanged]; if (ControlChanged != null) ControlChanged(this, e); } #endregion #region Overriden Method protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); if (Page != null) Page.RegisterRequiresPostBack(this); } #endregion #region Helper Methods // Take the value, and set the selected values of the private void SetSelected(string When) { string[] ResultList; Regex DateSplitter = new Regex("^\\d{1,2}\\/\\d{1,2}\\/\\d{4}$"); if (DateSplitter.IsMatch(When)) //The date has a good format { char divider = '/'; ResultList = When.Split(divider); SelectedMonth = Int32.Parse(ResultList[0]); SelectedDay = Int32.Parse(ResultList[1]); SelectedYear = Int32.Parse(ResultList[2]); } else //When must be empty or not recognizable, so set the listboxes to the empty value { SelectedDay = -1; SelectedMonth = -1; SelectedYear = -1; } } #endregion #region Create Control Components // Create the controls protected override void CreateChildControls() { // Clear out the control hiearchy Controls.Clear(); // see if we need to build up the hierarchy if (ViewState["ControlCount"] == null) CreateControlHierarchy(); } protected void CreateControlHierarchy() { int nYear; int i; //Create the days dropdown list, fill with array declared above dayList = new System.Web.UI.WebControls.DropDownList(); dayList.SelectedIndex = this.SelectedDay; dayList.ID = "Day"; dayList.DataSource = DayArray; dayList.DataBind(); this.Controls.Add(dayList); //Create the months dropdown list, fill with array declared above monthList = new System.Web.UI.WebControls.DropDownList(); monthList.SelectedIndex = this.SelectedMonth; monthList.ID = "Month"; monthList.DataSource = MonthArray; monthList.DataBind(); this.Controls.Add(monthList); //Fill years array based on the number of years back that was specified by the user YearArray = new string[this.YearsBack + this.YearsForward + 2]; //1 extra=blank item in list yearList = new System.Web.UI.WebControls.DropDownList(); nYear = DateTime.Now.Year; YearArray[0] = ""; for (i = 1; i <= YearArray.GetUpperBound(0); i++) { if ( i <= this.YearsBack ) YearArrayIdea [I] = Convert.ToString(nYear - this.YearsBack + (i - 1)); else YearArrayIdea [I] = Convert.ToString(nYear + (i-this.YearsForward-1)); // Add last year YearArray[YearArray.Length-1] = Convert.ToString(nYear + this.YearsForward); if (YearArrayIdea [I] == Convert.ToString(this.SelectedYear)) { //Set the selected index if a match is found yearList.SelectedIndex = i; } } yearList.ID = "Year"; yearList.DataSource = YearArray; yearList.DataBind(); this.Controls.Add(yearList); } #endregion #region Load Posted Data bool IPostBackDataHandler.LoadPostData(string postDataKey, NameValueCollection postCollection) { int Day = 0; int Month = 0; int Year = 0; bool Changed = false; string postedDay = postCollection[this.UniqueID.ToString() + "$Day"]; string postedMonth = postCollection[this.UniqueID.ToString() + "$Month"]; string postedYear = postCollection[this.UniqueID.ToString() + "$Year"]; if (!String.IsNullOrEmpty(postedDay)) { Day = Int32.Parse(postedDay); if (Day != this.SelectedDay) { this.SelectedDay = Day; Changed = true; } } else { if (this.SelectedDay != -1) { this.SelectedDay = -1; Changed = true; } } if (!String.IsNullOrEmpty(postedMonth)) { Month = Array.IndexOf(this.MonthArray, postedMonth); if (Month != this.SelectedMonth) { this.SelectedMonth = Month; Changed = true; } } else { if (this.SelectedMonth != -1) { this.SelectedMonth = -1; Changed = true; } } if (!String.IsNullOrEmpty(postedYear)) { Year = Int32.Parse(postedYear); if (Year != this.SelectedYear) { this.SelectedYear = Year; Changed = true; } } else { if (this.SelectedYear != -1) { this.SelectedYear = -1; Changed = true; } } if (this.SelectedDay == -1 || this.SelectedMonth == -1 || this.SelectedYear == -1) this.Value = ""; else this.Value = this.SelectedMonth.ToString() + "/" + this.SelectedDay.ToString() + "/" + this.SelectedYear.ToString(); return Changed; } void IPostBackDataHandler.RaisePostDataChangedEvent() { this.OnChanged(EventArgs.Empty); } #endregion } }

Here is the validator:
using System;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace CustomControls
{
    public class DatePickerValidator : BaseValidator
    {
        #region Private Fields
        #endregion

        protected override bool EvaluateIsValid()
        {
            string Value = this.GetControlValidationValue(this.ControlToValidate);
            return this.IsValidDate(Value);
        }

        private bool IsValidDate(string Item)
        {
            // to be built later
        }

        protected override void AddAttributesToRender(HtmlTextWriter writer)
        {
            if (this.DetermineRenderUplevel() && this.EnableClientScript)
            {
                base.AddAttributesToRender(writer);
                writer.AddAttribute("controltovalidate", this.ControlToValidate);
                writer.AddAttribute("evaluationfunction", "DatePickerIsValid");
                writer.AddAttribute("display", this.Display.ToString());
                writer.AddAttribute("style", "display:none");
                writer.AddAttribute("errormessage", this.ErrorMessage);
            }
        }

        protected override void OnPreRender(EventArgs e)
        {
            // MS Standard JavaScript File to include
            base.OnPreRender(e);

            if (this.DetermineRenderUplevel() && this.EnableClientScript)
            {
                this.SetClientScript();
            }
        }

        protected void SetClientScript()
        {
            StringBuilder script = new StringBuilder();
            script.Append("var errorType = 0;\r");
            script.Append("function DatePickerIsValid(val)\r");
            script.Append("{\r");
            script.Append("var CtrlToValidate = val.controltovalidate;\r");
            script.Append("var day = document.getElementById(CtrlToValidate + \"_Day\").value;\r");
            script.Append("var month = document.getElementById(CtrlToValidate + \"_Month\").value;\r");
            script.Append("var day = document.getElementById(CtrlToValidate + \"_Year\").value;\r");
            script.Append("\r");
            script.Append("var sExec = \"var bReturn = CheckDate(day,month,year);\"\r");
            script.Append("eval(sExec);\r");
            script.Append("\r");
            script.Append("if ( !bReturn )\r");
            script.Append("{\r");
            script.Append("val.innerHTML = displayError(errorType, CtrlToValidate);\r");
            script.Append("}\r");
            script.Append("else\r");
            script.Append("{\r");
            script.Append("val.innerHTML = \"\";\r");
            script.Append("}\r");
            script.Append("val.errormessage = val.innerHTML;\r");
            script.Append("return bReturn;\r");
            script.Append("}\r");
            script.Append("function isEmpty(aTextValue)\r");
            script.Append("{\r");
            script.Append("if ((aTextValue.length==0) || (aTextValue==null))\r");
            script.Append("return true;\r");
            script.Append("\r");
            script.Append("return false; \r");
            script.Append("}\r");
            script.Append("function CheckDate(day,month,year)\r");
            script.Append("{\r");
            script.Append("if ( isEmpty(day) || isEmpty(month) || isEmpty(year) )\r");
            script.Append("{\r");
            script.Append("errorType = 1;\r");
            script.Append("return false;\r");
            script.Append("}\r");
            script.Append("var daysPerMonth = getDaysofYear(year);\r");
            script.Append("monthIndex = GetMonthIndex(month);\r");
            script.Append("if ( day > daysPerMonth[monthIndex] )\r");
            script.Append("{\r");
            script.Append("errorType = 3;\r");
            script.Append("return false;\r");
            script.Append("}\r");
            script.Append("return true;\r");
            script.Append("}\r");
            script.Append("function GetMonthIndex(month)\r");
            script.Append("{\r");
            script.Append("if (month == \"January\")\r");
            script.Append("return (1);\r");
            script.Append("if (month == \"February\")\r");
            script.Append("return (2);\r");
            script.Append("if (month == \"March\")\r");
            script.Append("return (3);\r");
            script.Append("if (month == \"April\")\r");
            script.Append("return (4);\r");
            script.Append("if (month == \"May\")\r");
            script.Append("return (5);\r");
            script.Append("if (month == \"June\")\r");
            script.Append("return (6);\r");
            script.Append("if (month == \"July\")\r");
            script.Append("return (7);\r");
            script.Append("if (month == \"August\")\r");
            script.Append("return (8);\r");
            script.Append("if (month == \"September\")\r");
            script.Append("return (9);\r");
            script.Append("if (month == \"October\")\r");
            script.Append("return (10);\r");
            script.Append("if (month == \"November\")\r");
            script.Append("return (11);\r");
            script.Append("if (month == \"December\")\r");
            script.Append("return (12);\r");
            script.Append("}\r");   
            script.Append("function getDaysofYear(year)\r");
            script.Append("{\r");
            script.Append("if ( leapYear(year) == 1 )\r");
            script.Append("Leap = 29;\r");
            script.Append("else\r");
            script.Append("Leap = 28;\r");
            script.Append("\r");
            script.Append("daysofYear = new Array(0,31,Leap,31,30,31,30,31,31,30,31,30,31);\r");
            script.Append("\r");
            script.Append("return (daysofYear);\r");
            script.Append("}\r");
            script.Append("\r");
            script.Append("function leapYear(year)\r");
            script.Append("{\r");
            script.Append("if (((year%4)==0 && ((year%100)!=0) || ((year%400)==0))\r");
            script.Append("return (1);\r");
            script.Append("else\r");
            script.Append("return (0);\r");
            script.Append("} \r");
            script.Append("function displayError(nType,sName)\r");
            script.Append("{\r");
            script.Append("if (nType == 1)\r");
            script.Append("return 'Date Requried';\r");
            script.Append("if (nType == 3)\r");
            script.Append("return 'Invalid Date';\r");
            script.Append("}\r");
            this.Page.ClientScript.RegisterStartupScript(this.GetType(),"DateValidate",script.ToString());
        }

    }
}

Can you please help me?
Luis Abreu
Asp.Net User
Re: DatePicker control - urgent8/14/2005 4:17:25 PM

0/0

Hello.
what do you mean by it doesn't work? are you saying that the client side validation doesn't work? if that's what you're saying them if you're referring to firefox i must warn you that there's a bug on the validation script that makes client validation unusable in firefox.
--
Regards,
Luis Abreu
email: labreu_at_gmail.com
PT blog: http://weblogs.pontonetpt.com/luisabreu
EN blog:http://msmvps.com/blogs/luisabreu
http://www.pontonetpt.com
http://weblogs.pontonetpt.com/
SomeNewTricks2
Asp.Net User
Re: DatePicker control - urgent8/14/2005 7:24:32 PM

0/0

Hi:
What I have is that, I want to get the values of the selected day, mont, year and check the validation if there is a correct date selected. If not the javascript will set the ErrorMessage.

Can you help me please? What is the error in FireFox? I just want in my client side code, to get the selected value from the 3 ddls, then check the validatitiy of the date, that is all,

thank you
3 Items, 1 Pages 1 |< << Go >> >|



Search This Site:


Meet Our Sponsors:



Other Resources:

Date Picker and Atlas - asp.net_ajax.asp.net_ajax_ui - Web Programming ... Web Date Picker Server Control - ASP.NET Forums : The following sample ... urgent...errors. vs2005 web site deployment may be a dealbreaker : ...
DatePicker control - urgent - ng.asp-net-forum.windows-hosting_open_forum - Web Programming Newsgroups DatePicker control - urgent, > ROOT > NEWSGROUP > Asp.Net Forum > ... datepicker control - urgent. user control as a container. usercontrol and checkbox ...
it's really urgent ....datepicker control i'm using a date picker control from which i'm selecting fromdate and todate . i want to put ... it's really urgent ....datepicker control. Posted Date: 08 ...
p2p.wrox.com Forums - Urgent: Other control in Datagrid Subject: Urgent: Other control in Datagrid. Posted By: ... 11/27/2003 12:30:45 AM. How to add other controls like datepicker,combo box,checkbox,non editable ...
JavaScript DatePicker is not working i hope it depends on ur datetimepicker javascript control... Post Reply ... Previous : very urgent. Return to Discussion Forum. Post New Message. Category: ASP.NET ...
Date Picker and Atlas - asp.net_ajax.asp.net_ajax_ui - Web Programming ... Web Date Picker Server Control - ASP.NET Forums : The following sample ... urgent...errors. vs2005 web site deployment may be a dealbreaker : ...
use control, dll and javasript - ASP.NET Forums I have this JavaScript date picker that I wrote. ... volunteers so please keep out the (it's urgent | asap | reply me directly) stuff. ...
Web User Control (.ascx) Urgent - telerik Forum Telerik is a leading vendor of ASP.NET and Windows Forms UI components, Content ... DatePicker for Silverlight. DockPanel for Silverlight. MediaPlayer for Silverlight ...
Problem with DatePicker ?? The PRADO Community " Prado v3.x " General Discussion " Problem with DatePicker ? ... okay with the site but it have problem on fedora 8. Please help me, it urgent. ...
ASP.net Web Controls [Archive] - HighTechTalks DotNet Forums View Full Version : ASP.net Web Controls. Req: Date Picker control with AutoPostBack? ... Client Side scripting user control (0 replies) Urgent! ...
CodeProject: SqlWhereBuilder ASP.NET Server Control. Free source code ... For date field you can use any free DatePicker control. Ramesh Chinnasamy ... This is urgent. Many Great Thanks. Re: Value entry is user control. Mike Ellison ...
scriptmanager error urgent - telerik Forum DatePicker for Silverlight. DockPanel for Silverlight. MediaPlayer for Silverlight ... To resolve that error please add a ScriptManager control to your page: ...


 
All Times Are GMT