国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > .NET > 正文

用VisualC#.NET編寫服務器日期控件

2024-07-10 13:10:43
字體:
來源:轉載
供稿:網友

  一、序言

  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}:datepicker runat=server>")]
 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?true:(bool)viewstate["enabled"];
   }
   set
   {
    ensurechildcontrols();
    viewstate["enabled"] = value;
   }
  }

  public string buttonstyle
  {
   get
   {
    ensurechildcontrols();
    object o = viewstate["buttonsytle"];
    return (o == null)?_buttondefaultstyle:o.tostring();
   }
   set
   {
    ensurechildcontrols();
    viewstate["buttonsytle"] = value;
   }
  }

  [
   defaultvalue(calendarenum.longdatetime),
  ]

  public calendarenum dateformat
  {
   get
   {
    ensurechildcontrols();
    object format = viewstate["dateformat"];
    return format == null?calendarenum.longdatetime:(calendarenum)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+":dateinput";
   }
  }

  [
   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+":datebutton";
   }
  }

  public string buttontext
  {
   get
   {
    ensurechildcontrols();
    return viewstate["buttontext"] == null?_buttondefaulttext:(string)viewstate["buttontext"];
   }
   set
   {
    ensurechildcontrols();
    viewstate["buttontext"] = value;
   }
  }

  ///
  /// 將此控件呈現給指定的輸出參數。
  ///

  /// 要寫出到的 html 編寫器

  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");
  }
 }
}


  在上面的代碼中,需要注意以下幾點:

  ·如果你想將此控件的某些屬性供重載,則在聲明屬性前加上virtual關鍵字;

  ·在頁面輸出此控件時(即在render事件中),是先定義子控件的樣式或屬性,然后再產生子控件;

  ·在隱藏日歷子控件時,建議不要使用visible屬性來顯示/隱藏,使用visible=false隱藏時服務器端將不會將日歷控件html代碼發送給客戶端,會導致復合控件裝載日歷控件的表格會空白一塊出來,影響頁面的布局。所以使用樣式display=none設置來使日歷控件在客戶端隱藏,但是html代碼依然存在于頁面中;

  四、結束語

  在編寫服務器控件時,需要一定的html語言基礎,也要清楚.net程序的請求處理方式。服務器控件封裝了客戶端行為及邏輯判斷,無需開發者添加更多代碼。當然,有些地方使用服務器控件可以帶來方便,但是也增加了服務器的負荷。有時適當的結合javascript使一些代碼在客戶端運行,可提高web應用程序效率
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 定兴县| 井陉县| 抚宁县| 五家渠市| 碌曲县| 股票| 墨玉县| 松原市| 南投市| 廉江市| 海丰县| 剑阁县| 蒙阴县| 鲁甸县| 时尚| 蓬安县| 维西| 锡林郭勒盟| 清水县| 容城县| 贞丰县| 册亨县| 瑞安市| 调兵山市| 利川市| 毕节市| 昭苏县| 屯昌县| 永安市| 呼图壁县| 新津县| 潼南县| 漠河县| 仁寿县| 民丰县| 马公市| 嵊州市| 亳州市| 公主岭市| 奉化市| 陇西县|