无废话,上图

下载地址(源码):http://download.csdn.net/source/2596371

 

本控件是在 CustomControlFreak 的基础上修改的

本代码开源,欢迎指正,可随意修改.

 

 

Calendar.cs
  1 using System;
  2 using System.Drawing;
  3 using System.Collections.Generic;
  4 using System.Collections.Specialized;
  5 using System.ComponentModel;
  6 using System.Text;
  7 using System.Web;
  8 using System.Web.UI;
  9 using System.Web.UI.WebControls;
 10 using System.Globalization;
 11 [assembly: TagPrefix("XControl""xc")]
 12 namespace XControl
 13 {
 14     [ToolboxData("<{0}:Calendar runat=Server ></{0}:Calendar>")]
 15     [ToolboxBitmapAttribute(typeof(Calendar), "Resources.calendar.ico")]
 16     public class Calendar: WebControl, IPostBackDataHandler
 17     {
 18         #region Method
 19         public Calendar() 
 20         {
 21             this._culture = System.Globalization.CultureInfo.GetCultureInfo(cultureName);
 22         }
 23 
 24         private DateTime getDate()
 25         {
 26             if (!string.IsNullOrEmpty(HttpContext.Current.Request[InstanceID]))
 27             {
 28                 try
 29                 {
 30                     _defaultDate = DateTime.Parse(HttpContext.Current.Request[InstanceID].ToString());
 31                 }
 32                 catch { }
 33             }
 34             return _defaultDate;
 35         }
 36 
 37         protected override void RenderContents(HtmlTextWriter writer)
 38         {
 39 
 40             //加载JS 
 41             if (_divshow)
 42             {
 43                 writer.Write(string.Format("<script  src='{0}'></script>", Page.ClientScript.GetWebResourceUrl(this.GetType(), "XControl.Resources.lib.js")));
 44                 writer.Write(string.Format("<script type=\"text/javascript\">Dainty.setImg('{0}','{1}','{2}','{3}','{4}','{5}');</script>"
 45                     Page.ClientScript.GetWebResourceUrl(this.GetType(), "XControl.Resources.Today.gif"),
 46                     Page.ClientScript.GetWebResourceUrl(this.GetType(), "XControl.Resources.UY.gif"),
 47                     Page.ClientScript.GetWebResourceUrl(this.GetType(), "XControl.Resources.UM.gif"),
 48                     Page.ClientScript.GetWebResourceUrl(this.GetType(), "XControl.Resources.NM.gif"),
 49                     Page.ClientScript.GetWebResourceUrl(this.GetType(), "XControl.Resources.NY.gif"),
 50                     Page.ClientScript.GetWebResourceUrl(this.GetType(), "XControl.Resources.Close.gif")
 51                     ));            
 52             }
 53             //TextBox 控件呈现
 54             writer.AddAttribute(HtmlTextWriterAttribute.Type, "text");
 55             writer.AddAttribute(HtmlTextWriterAttribute.Name, InstanceID);
 56             writer.AddAttribute(HtmlTextWriterAttribute.Id, string.Format("txt{0}", InstanceID));
 57             writer.AddAttribute(HtmlTextWriterAttribute.Maxlength, "12");
 58 
 59 
 60             if (Width.Value > 0)
 61                 writer.AddAttribute(HtmlTextWriterAttribute.Style, string.Format("Width:{0}px"int.Parse(this.Width.Value.ToString())));
 62             
 63             if (_readonly)
 64             writer.AddAttribute(HtmlTextWriterAttribute.ReadOnly, "True");
 65 
 66             if (!string.IsNullOrEmpty(this._class))
 67                 writer.AddAttribute(HtmlTextWriterAttribute.Class, this._class);
 68             
 69             if (_divshow)
 70                 writer.AddAttribute(HtmlTextWriterAttribute.Onclick, string.Format("Dainty.exc(this,false);"));
 71 
 72             writer.AddAttribute(HtmlTextWriterAttribute.Value, Text);
 73             writer.RenderBeginTag(HtmlTextWriterTag.Input);
 74 
 75             writer.RenderEndTag();
 76 
 77         }
 78 
 79         protected override void OnPreRender(EventArgs e)
 80         {
 81             SelectedDate = getDate();
 82             base.OnPreRender(e);
 83         }
 84 
 85         #endregion
 86 
 87         #region 属性
 88         private string cultureName = CultureInfo.CurrentCulture.Name;
 89         private CultureInfo _culture;
 90         bool _readonly = false;
 91         bool _divshow = true;
 92         string _text = string.Empty;
 93         string _class = string.Empty;
 94         DateTime _defaultDate = DateTime.Today;
 95 
 96         /// <summary>
 97         /// ID
 98         /// </summary>
 99         private string InstanceID
100         {
101             get
102             {
103                 return string.IsNullOrEmpty(this.UniqueID) ? string.Empty : this.UniqueID.Replace("$""a");
104             }
105         }
106 
107         [Bindable(true), Category("自定义属性"), DefaultValue(false), Description("只读")]
108         public bool ReadOnly
109         {
110             get { return _readonly; }
111             set { try { _readonly = value; } catch { } }
112         }
113 
114         [Bindable(true), Category("自定义属性"), Description("默认选择日期")]
115         public DateTime SelectedDate
116         {
117             get { return _defaultDate.Date; }
118             set { try { _defaultDate = value; } catch { } }
119         }
120 
121         [Bindable(true), Category("自定义属性"), DefaultValue(""), Description("默认显示日期")]
122         public string Text
123         {
124             get
125             {
126                 try
127                 { getDate(); }
128                 catch { }
129                 return string.Format("{0}-{1}-{2}", _defaultDate.Year, _defaultDate.Month.ToString("00"), _defaultDate.Day);
130             }
131             internal set
132             {
133                 if (!string.IsNullOrEmpty(value))
134                 {
135                     try
136                     {
137                         string[] arr = value.Split(new char[] { ' ' })[0].Split(new char[] { '-' });
138                         if (arr.Length > 2)
139                             _defaultDate = new DateTime(Int32.Parse(arr[0]), Int32.Parse(arr[1]), Int32.Parse(arr[2]));
140                     }
141                     catch { throw new Exception("日期格式不正确"); }
142                 }
143                 throw new Exception("日期格式不正确");
144             }
145         }
146 
147         [Bindable(true), Category("Appearance"), DefaultValue(true), Description("是否启用")]
148         public override bool Enabled
149         {
150             get
151             {
152                 return base.Enabled;
153             }
154             set
155             {
156                 base.Enabled = _divshow = value;
157             }
158         }
159 
160         public override Unit Height
161         {
162             get{return base.Height;}
163             set{/*base.Height = value;*/}
164         }
165 
166         [Bindable(true), Category("Appearance"), DefaultValue(true), Description("控件外观")]
167         public override string CssClass
168         {
169             get
170             {
171                 return this._class;
172             }
173             set
174             {
175                 this._class = value;
176             }
177         }
178 
179         #endregion
180 
181         #region IPostBackDataHandler 成员
182 
183         public virtual bool LoadPostData(string PostDataKey, NameValueCollection postCollection)
184         {
185             Text = postCollection[PostDataKey];
186             return false;
187         }
188 
189         public virtual void RaisePostDataChangedEvent()
190         {
191             //empty
192         }
193 
194         #endregion
195     }
196 }
197

 

 

lib.js
  1 //<![CDATA[
  2 if (!document.getElementById("Xc_MainLayer")) {
  3             document.writeln('<div id=Xc_MainLayer Author=x style="position: absolute;float:none; width: auto;border:1px #8A99BA solid ;height:auto; cursor:default;z-index: 9998; display: none;font-family:Sans-Serif Arial; ">');
  4             document.writeln('<div id=Xc_tmpLayer  Author=x  style="position:absolute;display:none;font-size:12px;height:auto;margin-left:2px;background-color:#FFFFFF;border:1px #333 solid;float:none;"></div>');
  5             document.writeln('<table border=0 cellspacing=1 cellpadding=0 width=180 height=auto bgcolor=#FFFFFF onselectstart="return false">');
  6             document.writeln('<tr Author=x><td height=23 bgcolor=#FFFFFF>');
  7             document.writeln('<table border=0 cellspacing=1 cellpadding=0 width="100%" height=23 bgcolor=#18AC18 style=\"font-size:8pt;\"><tr align=center >');
  8             document.writeln('<td width=15 align=center Author=x ><img id=\"cToday\" src=\"\" style=\"boder:0px;cursor:pointer\" onclick="Dainty.Today()" title=\"今天\" Author=x /></td>');
  9             document.writeln('<td width=10 align=center Author=x ><img id=\"cUyear\" src=\"\" style=\"boder:0px;cursor:pointer\" onclick="Dainty.PrevY()" title=\"前一年\" Author=x /></td>');
 10             document.writeln('<td width=10 align=center Author=x ><img id=\"cUmonth\" src=\"\" style=\"boder:0px;cursor:pointer\" onclick="Dainty.PrevM()" title="前一月" Author=x /></td>');
 11             document.writeln('<td width=auto align=center Author=x><div style="float:none;text-align:center;width:auto;cursor:default;">');
 12             document.writeln('<span Author=x id=YearHead onmouseover="this.style.backgroundColor=\'white\'" onmouseout="this.style.backgroundColor=\'\'" title="点击这里选择年份" onclick="Dainty.selectY(this.innerHTML)" style="cursor:default;float:none;width:auto;font-size:12px;"></span>');
 13             document.writeln('<span style=\'width:auto;float:none;\'>年</span>');
 14             document.writeln('<span id=MonthHead Author=x onmouseover="style.backgroundColor=\'white\'" onmouseout="style.backgroundColor=\'\'" title="点击这里选择月份" onclick="Dainty.selectM(this.innerHTML)" style="width:auto;display:inline-block;font-family:sans-serif;float:none;font-size:12px;cursor:default;"></span>');
 15             document.writeln('<span style=\'width:auto;float:none;\'>月</span></div></td>');
 16             document.writeln('<td width=10 align=center Author=x ><img id=\"cNmonth\" src=\"\" style=\"boder:0px;cursor:pointer\" onclick="Dainty.NextM()" title="后一月" Author=x /></td>');
 17             document.writeln('<td width=10 align=center Author=x ><img id=\"cNyear\" src=\"\" style=\"boder:0px;cursor:pointer\" onclick="Dainty.NextY()" title="后一年" Author=x /></td>');
 18             document.writeln('<td width=15 align=center Author=x ><img id=\"c_Close\" src=\"\" style=\"boder:0px;cursor:pointer\" onclick="Dainty.Close()" title="关闭" Author=x /></td>');
 19             document.writeln('</tr></table></td></tr><tr valign=top><td width=100% height=120 align=center  Author=x>');
 20             document.writeln('<table border=0 cellspacing=1 cellpadding=0 width=140 height=120 bgcolor=#FFFFFF  style="font-size:12px;font-family:Sans-Serif Arial;">');
 21             document.writeln('<tr align=center><td  Author=x>日</td>');
 22             document.writeln('<td  Author=x>一</td><td  Author=x>二</td>');
 23             document.writeln('<td  Author=x>三</td><td  Author=x>四</td>');
 24             document.writeln('<td  Author=x>五</td><td  Author=x>六</td></tr>');
 25             var n = 0;
 26             for (j = 0; j < 5; j++) {
 27                 document.writeln(' <tr align=center  Author=x>');
 28                 for (i = 0; i < 7; i++) {
 29                     document.writeln('<td id=Xc_Day' + n + ' style="font-size:8pt;font-family: Arial;color:#000;" Author=x></td>');
 30                     n++;
 31                 }
 32                 document.writeln('</tr>');
 33             }
 34             document.writeln('<tr align=center  Author=x><td align=center Author=x  style="font-size:8pt;font-family:Arial;" id=Xc_Day35></td>');
 35             document.writeln('</tr></table></td></tr></table></div>');
 36         }
 37 
 38 var Dainty = {
 39     outObject: null,
 40     $: function(id) { return document.getElementById(id); },
 41     boTime: false,
 42     ID: "",
 43     MonHead: [312831303130313130313031], //定义阳历中每个月的最大天数
 44     theYear: new Date().getFullYear(), //定义年的变量的初始值
 45     theMonth: new Date().getMonth() + 1//定义月的变量的初始值
 46     theDay: new Date().getDate(),
 47     theTime: new Date().toLocaleTimeString(),
 48     wDay: new Array(37),
 49     loc: function getPos(o, sProp) { var i = 0while (o != null) { i += o["offset" + sProp]; o = o.offsetParent; } return i; },
 50     Close: function() { this.$("Xc_MainLayer").style.display = "none"this.$("Xc_tmpLayer").style.display = "none"; },
 51     wHead: function(yy, mm) { this.$("YearHead").innerHTML = yy; this.$("MonthHead").innerHTML = mm; },
 52     isPinY: function(year) { return (0 == year % 4 && ((year % 100 != 0|| (year % 400 == 0))); }, //判断是否闰平年           //定义写日期的数组
 53     selectY: function(strYear) {
 54     if (this.$("Xc_tmpLayer").style.display == "block")
 55         this.$("Xc_tmpLayer").style.display = "none";
 56         else {
 57             if (strYear.match(/\D/!= null) { alert("年份输入参数不是数字!"); return; }
 58             var m = (strYear) ? strYear : new Date().getFullYear();
 59             if (m < 1000 || m > 9999) { alert("年份值不在 1000 到 9999 之间!"); return; }
 60             var n = m - 5;
 61             if (n < 1000) n = 1000;
 62             if (n + 10 > 9999) n = 9974;
 63             var selectInnerHTML = "";
 64             for (var i = n; i < n + 11; i++) {
 65                 var str1 = i == m ? "#CCC" : "#FFFFFF";
 66                 selectInnerHTML += "<div Author=x onclick='Dainty.theYear = this.innerHTML; Dainty.setDay(Dainty.theYear,Dainty.theMonth);Dainty.$(\"Xc_tmpLayer\").style.display=\"none\";'";
 67                 selectInnerHTML += " onmousemove=this.style.backgroundColor='#ccc' onmouseout=\"this.style.backgroundColor='" + str1 + "';\" ";
 68                 selectInnerHTML += " style='width:auto;cursor:pointer;background-color:" + str1 + "'> " + i + "</div>\r\n";
 69             }
 70             this.$("Xc_tmpLayer").innerHTML = selectInnerHTML;
 71             this.$("Xc_tmpLayer").style.display = "block";
 72             this.$("Xc_tmpLayer").style.width = "30px";
 73             this.$("Xc_tmpLayer").style.top = 18 + "px";
 74             this.$("Xc_tmpLayer").style.left = 50 + "px";
 75         }
 76     },
 77     selectM: function(strMonth) {
 78     if (this.$("Xc_tmpLayer").style.display == "block")
 79         this.$("Xc_tmpLayer").style.display = "none";
 80         else {
 81             if (strMonth.match(/\D/!= null) { alert("月份输入参数不是数字!"); return; }
 82             var m = (strMonth) ? strMonth : new Date().getMonth() + 1;
 83             var selectInnerHTML = "";
 84             for (var i = 1; i < 13; i++) {
 85                 var str1 = i == m ? "#CCC" : "#FFFFFF";
 86                 selectInnerHTML += "<div Author=x onclick='Dainty.theMonth =this.innerHTML; Dainty.setDay(Dainty.theYear,Dainty.theMonth);Dainty.$(\"Xc_tmpLayer\").style.display=\"none\";'";
 87                 selectInnerHTML += " onmousemove=this.style.backgroundColor='#ccc' onmouseout=\"this.style.backgroundColor='" + str1 + "';\" ";
 88                 selectInnerHTML += " style='width:99%;float:none;cursor:pointer;background-color:" + str1 + "'> " + i + "</div>\r\n";
 89             }
 90             this.$("Xc_tmpLayer").innerHTML = selectInnerHTML;
 91             this.$("Xc_tmpLayer").style.display = "block";
 92             this.$("Xc_tmpLayer").style.width = "15px";
 93             this.$("Xc_tmpLayer").style.top = 18 + "px";
 94             this.$("Xc_tmpLayer").style.left = 95 + "px";
 95         }
 96     },
 97     getMonthN: function(year, month) { return ((month == 2&& this.isPinY(year)) ? this.MonHead[month - 1+ 1 : this.MonHead[month - 1]; }, //闰年二月为29天
 98     getDaw: function(day, month, year) { return new Date(year, month - 1, day).getDay() / 7; }, //求某天的星期几
 99     PrevY: function() { if (this.theYear > 999 && this.theYear < 10000) { this.theYear--; } else { alert("年份超出范围(1000-9999)!"); } this.setDay(this.theYear, this.theMonth); }, //往前翻 Year
100     PrevM: function() { if (this.theMonth > 1) { this.theMonth-- } else { this.theYear--this.theMonth = 12; } this.setDay(this.theYear, this.theMonth); }, //往前翻月份
101     NextY: function() { if (this.theYear > 999 && this.theYear < 10000) { this.theYear++; } else { alert("年份超出范围(1000-9999)!"); } this.setDay(this.theYear, this.theMonth); }, //往后翻 Year
102     NextM: function() { if (this.theMonth == 12) { this.theYear++this.theMonth = 1 } else { this.theMonth++ } this.setDay(this.theYear, this.theMonth); }, //往后翻月份
103     Today: function() { this.theYear = new Date().getFullYear(); this.theMonth = new Date().getMonth() + 1this.setDay(this.theYear, this.theMonth); }, //当日时间
104     select: function(n) { if (n == "") { return; } this.theDay = parseInt(n, 10); if (Dainty.outObject) { var yy = this.theYear; var mm = this.theMonth; var time = this.boTime ? this.theTime : ""if (mm < 10) { mm = "0" + parseInt(mm, 10); } if (!n) { Dainty.outObject.value = ""return; } if (n < 10) { n = "0" + n; } Dainty.outObject.value = yy + "-" + mm + "-" + n + " " + time; this.Close(); } else { this.Close(); alert("您所要输出的控件对象并不存在!"); } },
105     setDay: function(yy, mm) {         //输出日期表格
106         this.wHead(yy, mm);
107         this.$("Xc_tmpLayer").style.display = "none";
108         for (var i = 0; i < 37; i++) { this.wDay[i] = "" };  //将显示框的内容全部清空
109         var day1 = 1, firstday = new Date(yy, mm - 11).getDay();  //某月第一天的星期几
110         for (var i = firstday; day1 < this.getMonthN(yy, mm) + 1; i++) { this.wDay[i] = day1; day1++; }
111         var ty, tm, td = 0;
112         if (this.outObject.value.length > 0) {
113             var arr = this.outObject.value.split(" ")[0].split("-");
114             if (arr.length > 2) {
115                 ty = arr[0];
116                 tm = arr[1];
117                 td = arr[2];
118             }
119         }
120         for (var i = 0; i < 37; i++) {
121             var da = document.getElementById("Xc_Day" + i);   //书写新的一个月的日期星期排列
122             if (da) {
123                 if (this.wDay[i] != "") {
124                     da.innerHTML = this.wDay[i];
125                     da.style.backgroundColor = "#FFFFFF";
126                     if (yy == ty && mm == tm && this.wDay[i] == td)
127                         da.style.backgroundColor = "#CCC";
128                     if (yy == new Date().getFullYear() && mm == new Date().getMonth() + 1 && this.wDay[i] == new Date().getDate())
129                         da.style.backgroundColor = "#FFFF99";
130                     da.style.cursor = "pointer"
131                     da.onclick = function(e) { Dainty.select(this.innerHTML); };
132                 }
133                 else {
134                     da.innerHTML = "";
135                     da.style.backgroundColor = "";
136                     da.style.cursor = "default"
137                 }
138             }
139         }
140     },
141     setImg: function(today, Uy, Um, Nm, Ny, Close) { this.$("cToday").src = today; this.$("cUyear").src = Uy; this.$("cUmonth").src = Um; this.$("cNmonth").src = Nm; this.$("cNyear").src = Ny; this.$("c_Close").src = Close; },
142     exc: function(obj, btime) {
143         if (arguments.length > 3 || arguments.length < 1) { alert("对不起!您回传本控件参数不正確!"); return; }
144         if (obj) {
145             if (obj.value.length > 0) {
146                 var arr = obj.value.split(" ")[0].split("-");
147                 if (arr.length > 2) {
148                     if (arr[0< 1800 || arr[0> 3000 || arr[1> 12 || arr[1< 1 || arr[2> 31 || arr[2< 1)
149                         alert("输入日期不正确");
150                     else {
151                         this.theYear = arr[0];
152                         this.theMonth = arr[1];
153                         this.theDay = arr[2];
154                     }
155                 }
156             }
157             this.outObject = obj;      //指定要賦值的控件
158             var objDay = this.$("Xc_MainLayer");
159             objDay.style.top = this.loc(obj, "Top"+ +20 + "px";
160             objDay.style.left = this.loc(obj, "Left"+ "px";
161             objDay.style.display = "block";
162             this.boTime = btime;
163             this.setDay(this.theYear, this.theMonth);
164             document.onclick = function(e) { e = window.event || e; var srcEm = e.srcElement || e.target; with (srcEm) { if (!(tagName == "INPUT" || getAttribute("Author"))) { objDay.style.display = "none"; Dainty.$("Xc_tmpLayer").style.display = "none"; } } }
165             document.onkeydown = function(e) { e = window.event || e; var kCode = e.charCode || e.keyCode; if (kCode == 27) { objDay.style.display = "none"; Dainty.$("Xc_tmpLayer").style.display = "none"; } }
166         }
167     }
168 };
169 //]]>

 

 

posted on 2011-02-16 14:16  工程兵  阅读(794)  评论(1编辑  收藏  举报