用Visual C#.NET编写服务器日期控件(转载自http://www.itpub.net/813347.html)

一、序言
  Visual C#.NET是微软公司出品的一种新的编程语言(以下简称C#),它继承了C语言的一些特性,也加入了一些新的元素。以前用过Delphi开发程序的人可能刚开始使用C#的时候,对其有一种似曾相识的感觉(至少包括我)。是的,C#语言的创始人正是以前在Borland公司开发出Delphi语言的Anders Hejlsberg。在我开始使用C#开发程序时,就觉得它是一款很棒的开发Windows Form & Web程序的RAD工具。
在开发Web程序方面,C#的出现打破了以前的网页开发模式,实现了与开发Windows Form程序一样的所见即所得   
的功能。C#提供了一些常用的Web Form Control供开发人员使用,并且只需将控件拖入页面中即可,非常简单。但有时这些控件也不能满足开发人员的需要,需要开发人员自己编写用户控件(User Control)或自定义控件(Custom Control)来满足需求。在这里,我将讲解如何在C#中开发服务器控件。

  二、预备知识

  在C#中可以开发两种服务器控件,一个是用户控件(User Control)和自定义控件(Custom Control)。用户控件的本质与页面文件(aspx文件)差不多,是可被其它aspx页面重复使用的HTML代码段,当然它也包括后台代码(Code-behind),后缀名是ascx。所以在开发一些公用的静态页面时(例如页头,页脚)经常用到,但它的缺点是不易继承,不易分发,无法编译成二进制代码来进行部署。但是自定义控件的功能就强大许多,它可以被编译成二进制代码(DLL文件),可以被扩展、继承、分发。就像Web Form Control一样,其实它们每个控件就是一个DLL文件。

  开发用户控件比较简单,就像编写一个aspx页面一样,在这里就不介绍了。本文对象是自定义控件。服务器控件的基类是System.Web.UI.Control。如果要开发可视化的服务器控件,那我们需要从System.Web.UI.WebControls来继承,否则从System.Web.UI.Control继承。

  服务器控件在设计时以runat=”server”脚本代码嵌入到aspx文件中来表示此控件是在服务器端运行的。在服务器控件所在页面提交回传(PostBack)过程中是依靠ViewState(视图状态)来维护控件状态的。所以我们在设计服务器控件属性时,其值应保存在ViewState中。

  三、代码编写

  C#中有一个日历控件Calendar,但是现在我需要一个可以下拉的日历控件,并且初始时不显示日历,当我点击下拉按钮时才弹出,并且当选择了日期,日历会自动隐藏且选择的日期值会显示到相应的输入框中。显然Calendar控件不能满足我的需要,但是稍后我会在我的自定义控件中用到它。

  首先新建项目,在项目类型中选择Visual C#项目,在模板列表中选择Web控件库,输入项目名称AquaCalendar,然后选择项目所在目录,点击【确定】按钮。C#将会生成基本的框架代码。将项目中的类文件和类名改名为DatePicker(即日期控件的类名)。由于DatePicker是可视化控件,所以我们必须从System.Web.UI.WebControls继承。并且它包括一个输入框,一个按钮和日历控件,需要在DatePicker类中声明它们。像这种以多个服务器控件组合的控件成为复合控件。代码如下,比较重要的方法和代码在注释中会加以说明:

using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
using System.Drawing;

namespace AquaCalendar
{
 [DefaultProperty("Text", //在属性工具箱中显示的默认属性
 ToolboxData("<{0}atePicker runat=server></{0}atePicker>"]
 public class DatePicker : System.Web.UI.WebControls.WebControl , IPostBackEventHandler
 {
  //选择日期按钮的默认样式
  private const string _BUTTONDEFAULTSTYLE = "BORDER-RIGHT: gray 1px solid; BORDER-TOP: gray 1px solid; BORDER-LEFT: gray 1px solid; CURSOR: hand; BORDER-BOTTOM: gray 1px solid;";

  //按钮默认文本

  private const string _BUTTONDEFAULTTEXT = "...";
  private System.Web.UI.WebControls.Calendar _Calendar;

  public override ControlCollection Controls
  {
   get
   {
    EnsureChildControls(); //确认子控件集都已被创建
    return base.Controls;
   }
  }

  //创建子控件(服务器日历控件)

  protected override void CreateChildControls()
  {
   Controls.Clear();
   _Calendar = new Calendar();
   _Calendar.ID = MyCalendarID;
   _Calendar.SelectedDate = DateTime.Parse(Text);
   _Calendar.TitleFormat = TitleFormat.MonthYear;
   _Calendar.NextPrevFormat = NextPrevFormat.ShortMonth;
   _Calendar.CellSpacing = 0;
   _Calendar.Font.Size = FontUnit.Parse("9pt";
   _Calendar.Font.Name = "Verdana";
   _Calendar.SelectedDayStyle.BackColor = ColorTranslator.FromHtml("#333399";
   _Calendar.SelectedDayStyle.ForeColor = ColorTranslator.FromHtml("White";
   _Calendar.DayStyle.BackColor = ColorTranslator.FromHtml("#CCCCCC";
   _Calendar.TodayDayStyle.BackColor = ColorTranslator.FromHtml("#999999";
   _Calendar.TodayDayStyle.ForeColor = ColorTranslator.FromHtml("Aqua";
   _Calendar.DayHeaderStyle.Font.Size = FontUnit.Parse("8pt";
   _Calendar.DayHeaderStyle.Font.Bold = true;
   _Calendar.DayHeaderStyle.Height = Unit.Parse("8pt";
   _Calendar.DayHeaderStyle.ForeColor = ColorTranslator.FromHtml("#333333");
   _Calendar.NextPrevStyle.Font.Size = FontUnit.Parse("8pt");
   _Calendar.NextPrevStyle.Font.Bold = true;
   _Calendar.NextPrevStyle.ForeColor = ColorTranslator.FromHtml("White");
   _Calendar.TitleStyle.Font.Size = FontUnit.Parse("12pt");
   _Calendar.TitleStyle.Font.Bold = true;
   _Calendar.TitleStyle.Height = Unit.Parse("12pt");
   _Calendar.TitleStyle.ForeColor = ColorTranslator.FromHtml("White");
   _Calendar.TitleStyle.BackColor = ColorTranslator.FromHtml("#333399");
   _Calendar.OtherMonthDayStyle.ForeColor = ColorTranslator.FromHtml("#999999");
   _Calendar.NextPrevFormat = NextPrevFormat.CustomText;
   _Calendar.NextMonthText = "下月";
   _Calendar.PrevMonthText = "上月";
   _Calendar.Style.Add("display","none"); //默认不显示下拉日历控件
   _Calendar.SelectionChanged += new EventHandler(_Calendar_SelectionChanged);
   this.Controls.Add(_Calendar);
  }
  [
   Category("Appearance"), //该属性所属类别,参见图
   DefaultValue(""), //属性默认值
   Description("设置该日期控件的值。") //属性的描述
  ]

  public string Text
  {
   get
   {
    EnsureChildControls();
    return (ViewState["Text"] == null)?System.DateTime.Today.ToString("yyyy-MM-dd"):ViewState["Text"].ToString();
   }
   set
   {
    EnsureChildControls();
    DateTime dt = System.DateTime.Today;
    try
    {
     dt = DateTime.Parse(value);
    }
    catch
    {
     throw new ArgumentOutOfRangeException("请输入日期型字符串(例如:1981-04-29)!");
    }

    ViewState["Text"] = DateFormat == CalendarEnum.LongDateTime?dt.ToString("yyyy-MM-dd"):dt.ToString("yyyy-M-d");
   }
  }

  //重载服务器控件的Enabled属性,将选择日期按钮变灰(禁用)

  public override bool Enabled
  {
   get
   {
    EnsureChildControls();
    return ViewState["Enabled"] == null?truebool)ViewState["Enabled"];
   }
   set
   {
    EnsureChildControls();
    ViewState["Enabled"] = value;
   }
  }

  public string ButtonStyle
  {
   get
   {
    EnsureChildControls();
    object o = ViewState["ButtonSytle"];
    return (o == null)?_BUTTONDEFAULTSTYLE.ToString();
   }
   set
   {
    EnsureChildControls();
    ViewState["ButtonSytle"] = value;
   }
  }

  [
   DefaultValue(CalendarEnum.LongDateTime),
  ]

  public CalendarEnum DateFormat
  {
   get
   {
    EnsureChildControls();
    object format = ViewState["DateFormat"];
    return format == null?CalendarEnum.LongDateTimeCalendarEnum)format;
   }
   set
   {
    EnsureChildControls();
    ViewState["DateFormat"] = value;
    DateTime dt = DateTime.Parse(Text);
    Text=DateFormat == CalendarEnum.LongDateTime?dt.ToString("yyyy-MM-dd"):dt.ToString("yyyy-M-d");
   }
  }

  [
   Browsable(false),
   DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
  ]

  public string MyCalendarID //复合控件ID
  {
   get
   {
    EnsureChildControls();
    return this.ClientID+"_MyCalendar";
   }
  }

  [
   Browsable(false),
   DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
  ]

  public string MyCalendarName //复合控件名称
  {
   get
   {
    EnsureChildControls();
    return this.UniqueID+":MyCalendar";
   }
  }

  [
   Browsable(false),
   DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
  ]

  public string DatePickerInputID //复合控件中输入框的ID
  {
   get
   {
    EnsureChildControls();
    return this.ClientID+"_DateInput";
   }
  }

  [
   Browsable(false),
   DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
  ]

  public string DatePickerInputName //复合控件中输入框的名称
  {
   get
   {
    EnsureChildControls();
    return this.UniqueID+"ateInput";
   }
  }

  [
   Browsable(false),
   DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
  ]

  public string DatePickerButtonID //复合控件中按钮的ID
  {
   get
   {
    EnsureChildControls();
    return this.ClientID+"_DateButton";
   }
  }

  [
   Browsable(false),
   DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
  ]

  public string DatePickerButtonName //复合控件中按钮的名称
  {
   get
   {
    EnsureChildControls();
    return this.UniqueID+"ateButton";
   }
  }

  public string ButtonText
  {
   get
   {
    EnsureChildControls();
    return ViewState["ButtonText"] == null?_BUTTONDEFAULTTEXTstring)ViewState["ButtonText"];
   }
   set
   {
    EnsureChildControls();
    ViewState["ButtonText"] = value;
   }
  }

  /// <summary>
  /// 将此控件呈现给指定的输出参数。
  /// </summary>
  /// <param name="output"> 要写出到的 HTML 编写器 </param>

  protected override void Render(HtmlTextWriter output)
  {
   //在页面中输出控件时,产生一个表格(二行二列),以下是表格的样式
   output.AddAttribute(HtmlTextWriterAttribute.Cellspacing, "0");
   output.AddAttribute(HtmlTextWriterAttribute.Border, "0");
   output.AddAttribute(HtmlTextWriterAttribute.Cellpadding, "0");

   output.AddStyleAttribute("LEFT", this.Style["LEFT"]);
   output.AddStyleAttribute("TOP", this.Style["TOP"]);
   output.AddStyleAttribute("POSITION", "absolute");

   if (Width != Unit.Empty)
   {
    output.AddStyleAttribute(HtmlTextWriterStyle.Width, Width.ToString());
   }
   else
   {
    output.AddStyleAttribute(HtmlTextWriterStyle.Width, "200px");
   }

   output.RenderBeginTag(HtmlTextWriterTag.Table); //输出表格
   output.RenderBeginTag(HtmlTextWriterTag.Tr); //表格第一行
   output.AddAttribute(HtmlTextWriterAttribute.Width, "90%");
   output.RenderBeginTag(HtmlTextWriterTag.Td);

   //以下是第一行第一列中文本框的属性及其样式设置

   if (!Enabled)
   {
    output.AddAttribute(HtmlTextWriterAttribute.ReadOnly, "true");
   }

   output.AddAttribute(HtmlTextWriterAttribute.Type, "Text");
   output.AddAttribute(HtmlTextWriterAttribute.Id, DatePickerInputID);
   output.AddAttribute(HtmlTextWriterAttribute.Name, DatePickerInputName);
   output.AddAttribute(HtmlTextWriterAttribute.Value, Text);
   output.AddStyleAttribute(HtmlTextWriterStyle.Width, "100%");
   output.AddStyleAttribute(HtmlTextWriterStyle.Height, "100%");
   output.AddStyleAttribute(HtmlTextWriterStyle.FontFamily, Font.Name);
   output.AddStyleAttribute(HtmlTextWriterStyle.FontSize, Font.Size.ToString());
   output.AddStyleAttribute(HtmlTextWriterStyle.FontWeight, Font.Bold?"bold":"");
   output.AddStyleAttribute(HtmlTextWriterStyle.BackgroundColor, ColorTranslator.ToHtml(BackColor));
   output.AddStyleAttribute(HtmlTextWriterStyle.Color, ColorTranslator.ToHtml(ForeColor));
   output.RenderBeginTag(HtmlTextWriterTag.Input); //输出文本框
   output.RenderEndTag();
   output.RenderEndTag();
   output.AddAttribute(HtmlTextWriterAttribute.Width, "*");
   output.RenderBeginTag(HtmlTextWriterTag.Td);

   //以下是第一行第二列中按钮的属性及其样式设置

   if (!Enabled)
   {
    output.AddAttribute(HtmlTextWriterAttribute.Disabled, "true");
   }

   output.AddAttribute(HtmlTextWriterAttribute.Type, "Submit");
   output.AddAttribute(HtmlTextWriterAttribute.Id, DatePickerButtonID);
   output.AddAttribute(HtmlTextWriterAttribute.Name, DatePickerButtonName);
   output.AddAttribute(HtmlTextWriterAttribute.Value, ButtonText);
   output.AddStyleAttribute(HtmlTextWriterStyle.Width, "100%");
   output.AddAttribute(HtmlTextWriterAttribute.Onclick, Page.GetPostBackEventReference(this)); //点击按钮时需要回传服务器来触发后面的OnClick事件

   output.AddAttribute(HtmlTextWriterAttribute.Style, ButtonStyle);
   output.RenderBeginTag(HtmlTextWriterTag.Input); //输出按钮
   output.RenderEndTag();
   output.RenderEndTag();

   output.RenderEndTag();
   output.RenderBeginTag(HtmlTextWriterTag.Tr);
   output.AddAttribute(HtmlTextWriterAttribute.Colspan, "2");
   output.RenderBeginTag(HtmlTextWriterTag.Td);
   _Calendar.RenderControl(output); //将日历子控件输出
   output.RenderEndTag();
   output.RenderEndTag();
   output.RenderEndTag();
  }

  //复合控件必须继承IpostBackEventHandler接口,才能继承RaisePostBackEvent事件

  public void RaisePostBackEvent(string eventArgument)
  {
   OnClick(EventArgs.Empty);
  }

  protected virtual void OnClick(EventArgs e)
  {
   //点击选择日期按钮时,如果日历子控件没有显示则显示出来并将文本框的值赋值给日历子控件
   if (_Calendar.Attributes["display"] != "")
   {
    _Calendar.SelectedDate = DateTime.Parse(Text);
    _Calendar.Style.Add("display","");
   }
  }

  //复合控件中的日历控件日期变化事件

  private void _Calendar_SelectionChanged(object sender, EventArgs e)
  {
   //当选择的日期变化时,将所选日期赋值给文本框并将日历子控件隐藏
   Text = _Calendar.SelectedDate.ToString();
   _Calendar.Style.Add("display","none");
  }
 }
}

Candyzhai

转载于:https://www.cnblogs.com/Silverlight_Team/archive/2009/03/29/1424549.html

用Visual C#.NET编写服务器日期控件相关推荐

  1. 一瞬间-自定义一个漂亮的日期控件

    因为项目,需要一个日期输入控件,目前没有看到有特别合适的,所以自己DIY了一个,比较匆忙,说是一瞬间搞定,可也搞了2个小时才搞定的.    虽然其中使用事件和代码不是很规范,但目前可以凑合能用啦!,放 ...

  2. python 日历控件_python selenium 处理时间日期控件(十六)

    测试过程中经常遇到时间控件,需要我们来选择日期,一般处理时间控件通过层级定位来操作或者通过调用js来实现. 1.首先我们看一下如何通过层级定位来操作时间控件. 通过示例图可以看到,日期控件是无法输入日 ...

  3. 根据从日期控件选定的时间以表格形式显示数据_VB项目开发FlexGrid控件使用讲解...

    FlexGrid控件使用介绍 大家好,在VB开发管理系统中,FlexGrid控件使用是非常普遍的.用FlexGrid ActiveX控件可以在 Visual Basic的窗体中创建一个电子数据表格,也 ...

  4. jquery日期控件使用,起止时间

    1.下载jQuery核心文件,datepicker是轻量级插件,只需jQuery的min版本就行了,然后到官网http://jqueryui.com/download下载jquery-ui压缩包(可以 ...

  5. My97DatePicker(WdatePicker)日期控件用法

    <code class="language-html">WdatePicker[html] view plain copy print? <meta http-e ...

  6. Android日期控件

    (请先认真读一下前两段,谢谢) 最近做了一个电商的Android原生项目,其中有一个酒店预订的功能,要实现一个日期控件,基本就是入住时间,离店时间,日期控件需要连续展示一年或者几年的按月份显示的连续视 ...

  7. 【基础篇】DatePickerDialog日期控件的基本使用(一)

    项目步骤: 1.首先在Main.xml布局文件中添加一个Button标签,用来点击显示日期控件,Main.xml内容如下: <RelativeLayout xmlns:android=" ...

  8. jQuery里面的datepicker日期控件默认是显示英文的,如何显示中文或其他语言呢?...

    jQuery里面的datepicker日期控件默认是显示英文的,如何让他显示中文或其他呢? [官方的写法]: (1)引入JS文件: <script type="text/javascr ...

  9. ASP.NET中 Calendar(日期控件)的使用

    ylbtech-ASP.NET-Control-Basic:Calendar(日期控件)的使用 ASP.NET中 Calendar(日期控件)的使用. 1.A,运行效果返回顶部 Calendar(日期 ...

  10. WebForm服务器验证控件与前端js自定义验证共同使用

        问题: 前端aspx页面中需要在button中添加OnClientClick事件后,这个OnClientClick所执行的自定义的客户端js验证:这个时候,所有的服务器验证控件都会失效!   ...

最新文章

  1. 千万QPS毫秒响应:快手数据中台建设实践
  2. MVC,MVP与MVVM
  3. vue 项目白屏解决方案
  4. mvc4 html.beginform,MVC4 Html.BeginForm在Internet Explorer中提交按钮 9不工
  5. 工作198:无法选中的状态一定要绑定在select上面
  6. 【转】调用约定__cdecl、__stdcall和__fastcall的区别
  7. java线程实现及线程池的使用
  8. 五.开发记录之ubuntu系统安装各个软件
  9. Webpack的基本配置
  10. ArcGIS教程:降雨量插值
  11. 【转】数据挖掘从入门到进阶
  12. hapi入门之Authentication篇
  13. 我的2020java社招岗面经,阿里巴巴社招面试经历(Java工程师方向)
  14. 开源集市@中关村|气氛热烈,完美收官!
  15. phpstorm多出屏幕代码换行/自动换行
  16. Racket实现数字与中文的转换算法三(程序测试)
  17. 微信测试说了多少次我爱你的软件,微信解封次数是几次?怎么解封?
  18. python爬虫翻页代码 豆瓣_Python爬虫 豆瓣动态页面的爬取
  19. 移动硬盘读不出来的处理办法
  20. Java小农养成记第二十天

热门文章

  1. 关键点提取:单目3D检测的点睛之笔
  2. 微信小程序公农历转换的实现
  3. 计算机历史浩荡几十载,细数那些影响时代的人和事
  4. CocosCreator之粒子动画入门:飞机尾焰
  5. word撰写论文时公式格式:公式居中,编号右对齐(编号上下居中或底部对齐);公式编号引用
  6. GAMES101现代计算机图形学入门-闫令琪-随堂笔记-Lecture 06 Rasterization 2 (Antialiasing and Z-Buffering)
  7. Android开发动态设置view宽度和高度layoutParams的单位问题
  8. Java越学越迷茫,应该怎么办?
  9. ssm+微信小程序基于小程序的医院预约挂号系统毕业设计源码260839
  10. git.exe push --progress origin master:master To https://192.168.3.145:10102/r/~lifan/tms-vue.git !