首页 > 开发 > 综合 > 正文

控件代码共享--日期选择控件

2024-07-21 02:24:06
字体:
来源:转载
供稿:网友
 

思路:实现日期年月日的选择
1、可以设定年的起止年份
2、排除不正确日期选择的可能
3、使用javascript实现控制
4、使用text属性方便获取设置日期值
=================================
代码如下:
using system;
using system.collections;
using system.collections.specialized;
using system.componentmodel;
using system.io;
using system.text;
using system.web.ui;
using system.web.ui.design.webcontrols;
using system.web.ui.webcontrols;

namespace jsy
{
/// <summary>
/// aspnetdate 选择输入日期控件
/// </summary>
[defaultproperty("text"),
parsechildren(false),
persistchildren(false),
description("专用于asp.net web应用程序的日期控件"),
designer(typeof(datedesigner)),
toolboxdata("<{0}:jsynetdate runat=server></{0}:jsynetdate>")]
public class jsynetdate:panel,inamingcontainer,ipostbackdatahandler
{
#region 属性
/// <summary>
/// 获取/设置日期值。
/// </summary>
[bindable(true),
browsable(true),
description("日期值"),
category("外观"),
defaultvalue("")]
public string text
{
get
{
if (viewstate["text"] != null)
{
return viewstate["text"].tostring();
}
else
{
if (isnull)
{
return "";
}
else
{
datetime date=system.datetime.today;
string str="";
switch (dateformat)
{
case "ymd":
str=date.tostring("yyyy-mm-dd",system.globalization.datetimeformatinfo.invariantinfo);
break;
case "ym":
str=date.tostring("yyyy-mm",system.globalization.datetimeformatinfo.invariantinfo);
break;
case "y":
str=date.year.tostring();
break;
}
return str;
}
}
}

set
{
if (value=="")
{
viewstate["text"] = "";
}
else if (dateformat=="ymd")
{
datetime date;
try
{
date=convert.todatetime(value);
}
catch
{
date=system.datetime.today;
}
string str = date.tostring("yyyy-mm-dd",system.globalization.datetimeformatinfo.invariantinfo);
if (str=="1900-01-01")
str="";
viewstate["text"] =str;
}
else
{
viewstate["text"] = value;
}
}
}
/// <summary>
/// 获取/设置日期值是否允许空。
/// </summary>
[browsable(true),
description("日期值是否允许空"),
category("布局"),
defaultvalue(false)]
public bool isnull
{
get
{
return (viewstate["isnull"]==null)?false:true;
}
set
{
if (value)
viewstate["isnull"]=true;
}
}
/// <summary>
/// 获取/设置日期值格式(ymd:年-月-日 ym:年-月 y:年)。
/// </summary>
[browsable(true),
description("日期值格式(ymd:年-月-日 ym:年-月 y:年)"),
category("布局"),
defaultvalue("ymd")]
public string dateformat
{
get
{
return (viewstate["dateformat"]==null)?"ymd":(string)viewstate["dateformat"];
}

set
{
viewstate["dateformat"]=value;
}
}
/// <summary>
/// 获取/设置日期值能否编辑。
/// </summary>
[browsable(true),
description("能否编辑"),
category("行为"),
defaultvalue(true)]
public override bool enabled
{
get
{
return (viewstate["enabled"]==null)?true:false;
}

set
{
if (!value)
viewstate["enabled"]=false;
}
}
/// <summary>
/// 获取/设置日期值中可供选择的年份长度。
/// </summary>
[browsable(true),
description("日期值中可供选择的年份长度"),
category("布局"),
defaultvalue(100)]
public int length
{
get
{
object obj=viewstate["length"];
return (obj==null)?100:(int)obj;
}

set
{
viewstate["length"]=value;
}
}
/// <summary>
/// 获取/设置选择年份的结束值。
/// </summary>
[browsable(true),
description("日期值中选择结束年份,当小于100时表示距今年数"),
category("布局"),
defaultvalue(0)]
public int end
{
get
{
object obj=viewstate["end"];
int y;
if (obj==null)
{
y=system.datetime.today.year;
}
else
{
y=(int)obj;
if (y<100)
{
y=system.datetime.today.year+y;
}
}
return y;
}

set
{
viewstate["end"]=value;
}
}
/// <summary>
/// 获取选择年份的开始值。
/// </summary>
[browsable(false),
designerserializationvisibility(designerserializationvisibility.hidden)]
public int start
{
get{return end-length;}
}

#endregion
#region 重写事件
/// <summary>
/// 重写onload 方法。
/// </summary>
/// <param name="e">包含事件数据的 <see cref="eventargs"/> 对象。</param>
protected override void onload(eventargs e)
{
if (page.ispostback)
{
string y=page.request.form[this.uniqueid+"_year"];
string m=page.request.form[this.uniqueid+"_month"];
string d=page.request.form[this.uniqueid+"_day"];
switch (dateformat)
{
case "ymd":
if (y=="" || m=="" || d=="")
{
text="";
}
else
{
text=y+"-"+m+"-"+d;
}
break;
case "ym":
if (y=="" || m=="")
{
text="";
}
else
{
text=y+"-"+m;
}
break;
case "y":
if (y=="")
{
text="";
}
else
{
text=y;
}
break;
}
}
base.onload(e);
}
/// <summary>
/// 重写<see cref="system.web.ui.webcontrols.webcontrol.addattributestorender"/> 方法,验证是否有form(runat=server)控件
/// </summary>
/// <param name="writer"></param>
protected override void addattributestorender(htmltextwriter writer)
{
if(this.page!=null)
this.page.verifyrenderinginserverform(this);
base.addattributestorender(writer);
}
/// <summary>
/// 重写<see cref="system.web.ui.control.onprerender"/>方法。
/// </summary>
/// <param name="e">包含事件数据的 <see cref="eventargs"/> 对象。</param>
protected override void onprerender(eventargs e)
{
string [email protected]"<script language='javascript'>

//原创:贾世义 日期:2005-08-16 免费共享 v1.0
//邮箱:[email protected]
//请尊重版权,可以随意使用,但请注明出处//

function inityear(pname,start,length,y)
{
  var selyear=eval('document.forms[0].'+pname+'_year');
  var n=selyear.length;
  selyear.length=n+length+1;
  for (i=0;i<=length;i++)
  {
selyear.options[n+i].value=(i+start);
selyear.options[n+i].text=(i+start);
  }
  if (y==0)
  {
selyear.selectedindex =0;
  }
  else
  {
if (y>start)
{
           if (y-start<=length)
   {
selyear.selectedindex = n+y-start;
   }
   else
  {
selyear.selectedindex = length;
  }
        }
  }
}

function initmonth(pname,m)
{
  var selmonth=eval('document.all.'+pname+'_month');
  var n=selmonth.length;
  selmonth.length=n+12;
  for (i=1;i<10;i++)
  {
selmonth.options[n+i-1].value='0'+i;
selmonth.options[n+i-1].text=i;
  }
  for (i=10;i<=12;i++)
  {
selmonth.options[n+i-1].value=i;
selmonth.options[n+i-1].text=i;
  }
  if (m==0)
  {
selmonth.selectedindex=0;
  }
  else
  {
selmonth.selectedindex = n+m-1;
  }
}

function initday(pname,d)
{
  var selday=eval('document.all.'+pname+'_day');
  var n=selday.length;
  selday.length=n+31;
  for (i=1;i<10;i++)
  {
selday.options[n+i-1].value='0'+i;
selday.options[n+i-1].text=i;
  }
  for (i=10;i<=31;i++)
  {
selday.options[n+i-1].value=i;
selday.options[n+i-1].text=i;
  }
  if (d==0)
  {
selday.selectedindex = 0;
  }
  else
  {
selday.selectedindex = n+d-1;
  }
  datechange(pname);
}

function datechange(pname)
{
 var selyear=eval('document.forms[0].'+pname+'_year');
 var year=selyear.options[selyear.selectedindex].value;
 if (year!='')
 {
 var selmonth=eval('document.all.'+pname+'_month');
 var month=selmonth.options[selmonth.selectedindex].value;
 if (month!='')
 {
   var date=new date(year,month,0);
   var day=date.getdate();
   var selday=eval('document.all.'+pname+'_day');
   var tmp=1;
   if (selday.selectedindex>0)
   {
tmp=selday.options[selday.selectedindex].value;
   }
   selday.length=day;
   for (i=1;i<10;i++)
   {
selday.options[i-1].value='0'+i;
selday.options[i-1].text=i;
   }
   for (i=10;i<=day;i++)
   {
selday.options[i-1].value=i;
selday.options[i-1].text=i;
   }
   if (tmp>day)
   {
selday.selectedindex=day-1;
   }
   else
   {
selday.selectedindex=tmp-1;
   }
 }
 }
}

</script>";
page.registerclientscriptblock("enabledays",strjs);
base.onprerender(e);
}
/// <summary>
/// 将此控件呈现给指定的输出参数。
/// </summary>
/// <param name="writer"> 要写出到的 html 编写器 </param>
protected override void render(htmltextwriter writer)
{
writer.write("<table border='0' cellpadding='0' cellspacing='0'><tr><td nowrap align='left'>");
int y=0;
int m=0;
int d=0;
string str=text;
if (str.length>=4)
{
y=convert.toint32(str.substring(0,4));
if (str.length>=7)
{
m=convert.toint32(str.substring(5,2));
if (str.length>=10)
{
d=convert.toint32(str.substring(8,2));
}
}
}
bool isdate=(dateformat=="ymd");
if (enabled)
{
bool isnull=isnull;
writer.write("<select name='"+this.uniqueid+"_year'");
if (isdate)
{
writer.write(" onchange=/"datechange('"+this.uniqueid+"')/"");
}
writer.write(">");
if (isnull)
{
writer.write("<option value=''></option>");
}
writer.write("</select>年");
if (dateformat.length>1)
{
writer.write("<select name='"+this.uniqueid+"_month'");
if (isdate)
{
writer.write(" onchange=/"datechange('"+this.uniqueid+"')/"");
}
writer.write(">");
if (isnull)
{
writer.write("<option value=''></option>");
}
writer.write("</select>月");
writer.write(@"
<script language='javascript'>
inityear('"+this.uniqueid+"',"+start.tostring()+","+length.tostring()+","+y.tostring()[email protected]");
initmonth('"+this.uniqueid+"',"+m.tostring()[email protected]");
</script>");
if (isdate)
{
writer.write("<select name='"+this.uniqueid+"_day'>");
if (isnull)
{
writer.write("<option value=''></option>");
}
writer.write("</select>日");
writer.write(@"
<script language='javascript'>
initday('"+this.uniqueid+"',"+d.tostring()[email protected]");
</script>");
}
}
}
else
{
if (y==0 || m==0)
{
writer.write("&nbsp;");
}
else
{
writer.write(y.tostring()+"年"+m.tostring()+"月");
if (d!=0)
{
writer.write(d.tostring()+"日");
}
}
}
writer.write("</td></tr></table>");
}

public event eventhandler textchanged;   

/// <summary>
/// 当由类实现时,为 asp.net 服务器控件处理回发数据。
/// </summary>
/// <param name="postdatakey">控件的主要标识符</param>
/// <param name="postcollection">所有传入名称值的集合</param>
/// <returns>如果服务器控件的状态在回发发生后更改,则为 true;否则为 false。</returns>
public virtual bool loadpostdata(string postdatakey, namevaluecollection postcollection)
{
string presentvalue = text;
string postedvalue = postcollection[postdatakey];

if (presentvalue == null || !presentvalue.equals(postedvalue))
{
text = postedvalue;
return true;
}

return false;
}

     
/// <summary>
/// 当由类实现时,用信号要求服务器控件对象通知 asp.net 应用程序该控件的状态已更改。
/// </summary>
public virtual void raisepostdatachangedevent()
{
ontextchanged(eventargs.empty);
}
     

protected virtual void ontextchanged(eventargs e)
{
if (textchanged != null)
textchanged(this,e);
}
#endregion

}


#region 控件设计器
/// <summary>
/// 服务器控件设计器。
/// </summary>
public class datedesigner:system.web.ui.design.webcontrols.paneldesigner
{
/// <summary>
/// 初始化 pagerdesigner 的新实例。
/// </summary>
public datedesigner()
{
this.readonly=true;
}
private jsynetdate wb;

/// <summary>
/// 获取用于在设计时表示关联控件的 html。
/// </summary>
/// <returns>用于在设计时表示控件的 html。</returns>
public override string getdesigntimehtml()
{

wb=(jsynetdate)component;
wb.text="";
stringwriter sw=new stringwriter();
htmltextwriter writer=new htmltextwriter(sw);
wb.rendercontrol(writer);
return sw.tostring();
}

/// <summary>
/// 获取在呈现控件时遇到错误后在设计时为指定的异常显示的 html。
/// </summary>
/// <param name="e">要为其显示错误信息的异常。</param>
/// <returns>设计时为指定的异常显示的 html。</returns>
protected override string geterrordesigntimehtml(exception e)
{
string errorstr="创建控件时出错:"+e.message;
return createplaceholderdesigntimehtml(errorstr);
}
}
#endregion
}
==================================
把以上代码保存为一个文件,如:jsynetdate.cs
使用csc /t:library /out:../bin/jsy.dll /r:system.web.dll /r:system.dll jsynetdate.cs编译即可
===================================
请多留宝贵意见,我会继续努力
使用举例
<%@ register tagprefix="cc1" namespace="jsy" assembly="jsy" %>
<%@ page language="c#"%>
<!doctype html public "-//w3c//dtd html 4.0 transitional//en" >
<html>
<head>
<title>webform1</title>
<meta name="generator" content="microsoft visual studio .net 7.1">
<meta name="code_language" content="c#">
<meta name="vs_defaultclientscript" content="javascript">
<meta name="vs_targetschema" content="http://schemas.microsoft.com/intellisense/ie5">
</head>
<body>
<form id="form1" method="post" runat="server">
<div align="center"><br/><br/><br/><br/><br/>
<cc1:jsynetdate id="jsynetdate1" length="50" isnull="true" runat="server"></cc1:jsynetdate>
<br/>
<asp:button id="button1" runat="server" text="button"></asp:button>
</div>
</form>
</body>
</html>


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表