用VisualC#.NET编写服务器日期控件

用VisualC#.NET编写服务器日期控件,第1张

用VisualC#.NET编写服务器日期控件,第2张

一.导言

视觉#。NET是微软公司推出的一种新的编程语言(以下简称C#),它继承了C语言的一些特性,并加入了一些新的元素。之前用过Delphi开发程序的人,可能在刚开始用C#的时候,对它有一种熟悉的感觉(至少包括我)。是的,C#语言的创始人是之前在Borland公司开发Delphi语言的安德斯·海尔斯伯格。当我开始使用C#开发程序时,我认为它是开发Windows窗体和Web程序的一个很棒的RAD工具。
在开发Web程序方面,C#的出现打破了以往的网页开发模式,实现并开发了Windows。

表单程序具有相同的所见即所得功能。# C提供了一些常用的Web表单控件供开发人员使用,只需将控件拖动到页面中即可,非常简单。但是有时候这些控件并不能满足开发者的需求,开发者需要编写用户控件或者自定义控件来满足需求。在这里,我将解释如何用C#开发服务器控件。

二、初步知识

在C#中可以开发两种服务器控件,一种是用户控件,一种是自定义控件。控件的本质类似于页面文件(ASPx文件)。它是一个HTML代码段,可以被其他aspx页面重用。当然也包括后缀为ascx的后台代码(Code-behind)。所以在开发一些公共静态页面(比如页眉页脚)的时候经常使用,但是它的缺点是不容易继承、分发和编译成二进制代码进行部署。但是自定义控件的功能要强大的多。可以编译成二进制代码(DLL文件),可以扩展、继承和分发。就像Web表单控件一样,它们的每个控件实际上都是一个DLL文件。

开发用户控件相对简单,就像写aspx页面一样,这里就不介绍了。这篇文章是一个自定义控件。服务器的基类是System。如果我们想开发可视化的服务器控件,那么我们需要继承System。否则我们将从系统继承。Web.UI .控件

在设计时,服务器将runat = "server "脚本代码嵌入到aspx文件中,以指示该控件正在服务器端运行。在回发到服务器控件所在页面的过程中,控件状态由ViewState维护。因此,当我们设计服务器控件属性时,其值应该保存在ViewState中。

第三,代码编写

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

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

使用系统;
使用系统。Web . UI
使用系统。Web . UI.WebControls
使用系统。组件模型;
使用系统。绘图;

命名空间aqua calendar
{
[default property(" Text "),//属性工具箱中显示的默认属性
toolbox data(" ")]
public class date picker:system . web . ui . web controls . web control,OstbackEventHandler
{
/选择日期按钮的默认样式
Private const string _ button default style = " border-right:gray 1 px solid;边框-:灰色1px纯色;左边框:灰色1px纯色;光标:手;底部边框:灰色1px纯色;";

//按钮默认文本

私有常量string _BUTTONDEFAULTTEXT = " ... ";
私有系统。web . ui . web controls . Calendar _ Calendar;

public override control collection Controls
{
get
{
EnsureChildControls();//确认所有子控件集都已创建
返回base。控制;
}
}

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

受保护的重写void CreateChildControls()
{
控件。clear();
_Calendar =新日历();
_日历。ID = MyCalendarID
_日历。SelectedDate = DateTime。解析(文本);
_日历。TitleFormat =标题格式。月份;
_日历。NextPrevFormat = NextPrevFormat。短月;
_日历。单元格间距= 0;
_日历。Font.Size = FontUnit。parse(" 9pt ");
_日历。Font . Name = " Verdana
_日历。SelectedDayStyle . back color = color translator。from html(" # 333399 ");
_日历。SelectedDayStyle . ForeColor = color translator。from html(" White ");
_日历。DayStyle . back color = color translator。from html(" # CCCCCC ");
_日历。TodayDayStyle . back color = color translator。from html(" # 999999 ");
_日历。TodayDayStyle . ForeColor = color translator。from html(" Aqua ");
_日历。day header style . font . size = font unit。parse(" 8pt ");
_日历。day header style . font . bold = true;
_日历。DayHeaderStyle.Height = Unit。parse(" 8pt ");
_日历。day header style . ForeColor = color translator。from html(" # 333333 ");
_日历。NextPrevStyle . font . size = font unit。parse(" 8pt ");
_日历。NextPrevStyle . Font.Bold = true
_日历。NextPrevStyle . ForeColor = color translator。from html(" White ");
_日历。TitleStyle.Font.Size = FontUnit。parse(" 12pt ");
_日历。TitleStyle . Font.Bold = true
_日历。TitleStyle.Height = Unit。parse(" 12pt ");
_日历。title style . ForeColor = color translator。from html(" White ");
_日历。title style . back color = color translator。from html(" # 333399 ");
_日历。OtherMonthDayStyle . ForeColor = color translator。from html(" # 999999 ");
_日历。NextPrevFormat = NextPrevFormat。CustomText
_ calendar.nextmountext = "下月";
_日历。PrevMonthText = "上个月";
_日历。Style.Add("display "," none ");//默认不显示下拉日历控件
_ calendar . selection change+= new eventhandler(_ calendar _ selection change);
这个。controls . Add(_ Calendar);
}
[
类别("外观"),//该属性的类别,见图
DefaultValue(" ",//属性默认值
说明("设置该日期控件的值。")//属性的描述
]

public string Text
{
get
{
EnsureChildControls();
return(ViewState[" Text "]= = null)?系统。DateTime . today . tostring(" yyyy-MM-DD "):ViewState[" Text "]。ToString();
}
set
{
EnsureChildControls();
DateTime dt = System。日期时间。今天;
try
{
dt = DateTime。解析(值);
}
catch
{
throw new argumentoutofrangeexception("请输入一个日期字符串(例如,1981年4月29日)!");
}

ViewState[" Text "]= date format = = calendar enum。LongDateTime?dt。ToString("yyyy-MM-dd"):dt。ToString(" yyyy-M-d ");
}
}

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

public override bool Enabled
{
get
{
EnsureChildControls();
返回视图状态["Enabled"] == null?true:(bool)ViewState[" Enabled "];
}
set
{
EnsureChildControls();
ViewState[" Enabled "]= value;
}
}

public string button style
{
get
{
EnsureChildControls();
object o = ViewState[" button syle "];
return (o == null)?_ BUTTONDEFAULTSTYLE:o . ToString();
}
set
{
EnsureChildControls();
ViewState[" button sytle "]= value;
}
}

[
default value(calendar enum。LongDateTime),
]

public calendar enum date format
{
get
{
EnsureChildControls();
object format = ViewState[" date format "];
返回格式== null?金盏花。LongDateTime:(CalendarEnum)格式;
}
set
{
EnsureChildControls();
ViewState[" date format "]= value;
DateTime dt =日期时间。解析(文本);
Text = date format = = calendar enum。LongDateTime?dt。ToString("yyyy-MM-dd"):dt。ToString(" yyyy-M-d ");
}
}

[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility。隐藏)
]

公共字符串MyCalendarID //复合控件ID
{
Get
{
InsureChildControls();
退这个。ClientID+" _ my calendar ";
}
}

[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility。隐藏)
]

公共字符串MyCalendarName //复合控件名
{
Get
{
InsureChildControls();
退这个。UniqueID+":my calendar ";
}
}

[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility。隐藏)
]

复合控件中输入框的公共字符串日期选取器输入ID//ID
{
Get
{
ensurechildcontrols();
退这个。ClientID+" _ date input ";
}
}

[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility。隐藏)
]

公共字符串日期选择器输入名称//复合控件中输入框的名称
{
get
{
ensurechildcontrols();
退这个。UniqueID+":date input ";
}
}

[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility。隐藏)
]

复合控件中按钮的公共字符串日期选取器button ID//ID
{
Get
{
InsureChildControls();
退这个。ClientID+" _ date button ";
}
}

[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility。隐藏)
]

公共字符串日期选取器按钮名称//复合控件中按钮的名称
{
get
{
ensurechildcontrols();
退这个。UniqueID+":date button ";
}
}

public string button text
{
get
{
EnsureChildControls();
返回视图状态["ButtonText"] == null?_ button default text:(string)ViewState[" button text "];
}
set
{
EnsureChildControls();
ViewState[" button text "]= value;
}
}

///
//将该控件呈现给指定的输出参数。
//
//要写入的HTML编写器

受保护的重写Void Render (HTMLTextWriter输出)
{
/当控件在页面中输出时,将生成一个表(两行两列)。下面是表格的style
output.add属性(htmltextwriteattribute . cellspacing," 0 ");
输出。add attribute(HtmlTextWriterAttribute。边框,“0”);
输出。add attribute(HtmlTextWriterAttribute。Cellpadding," 0 ");

输出。AddStyleAttribute("LEFT ",这个。style[" LEFT "]);
输出。AddStyleAttribute("),这个。style[" "]);
输出。AddStyleAttribute("POSITION "," absolute ");

如果(宽度!=单位。空)
{
输出。addstyle attribute(HtmlTextWriterStyle。宽度,宽度。ToString());
}
else
{
output。addstyle attribute(HtmlTextWriterStyle。宽度,“200 px”);
}

输出。RenderBeginTag(HtmlTextWriterTag。表);//输出表
output . renderbegintag(htmltextwritertag . tr);//表格的第一行
output . add attribute(htmltextwriteattribute . width," 90% ");
输出。RenderBeginTag(HtmlTextWriterTag。TD);

//下面是第一行第一列文本框的属性和样式设置。

如果(!Enabled)
{
输出。add attribute(HtmlTextWriterAttribute。ReadOnly,“真”);
}

输出。add attribute(HtmlTextWriterAttribute。类型,“文本”);
输出。add attribute(HtmlTextWriterAttribute。Id,DatePickerInputID);
输出。add attribute(HtmlTextWriterAttribute。姓名,DatePickerInputName);
输出。add attribute(HtmlTextWriterAttribute。值,文本);
输出。addstyle attribute(HtmlTextWriterStyle。宽度,“100%”;
输出。addstyle attribute(HtmlTextWriterStyle。身高,“100%”;
输出。addstyle attribute(HtmlTextWriterStyle。FontFamily,字体。姓名);
输出。addstyle attribute(HtmlTextWriterStyle。字体大小,字体。size . ToString());
输出。addstyle attribute(HtmlTextWriterStyle。字体粗细,字体。大胆?"粗体":");
输出。addstyle attribute(HtmlTextWriterStyle。背景颜色,颜色翻译。ToHtml(back color));
输出。addstyle attribute(HtmlTextWriterStyle。颜色,颜色翻译。ToHtml(ForeColor));
输出。RenderBeginTag(HtmlTextWriterTag。输入);//输出文本框
输出。RenderEndTag();
输出。RenderEndTag();
输出。add attribute(HtmlTextWriterAttribute。宽度,“*”);
输出。RenderBeginTag(HtmlTextWriterTag。TD);

//下面是第一行第二列按钮的属性和样式设置。

如果(!Enabled)
{
输出。add attribute(HtmlTextWriterAttribute。禁用,“真”);
}

输出。add attribute(HtmlTextWriterAttribute。类型,“提交”);
输出。add attribute(HtmlTextWriterAttribute。Id,DatePickerButtonID);
输出。add attribute(HtmlTextWriterAttribute。Name,DatePickerButtonName);
输出。add attribute(HtmlTextWriterAttribute。Value,button text);
输出。addstyle attribute(HtmlTextWriterStyle。宽度,“100%”;
输出。add attribute(HtmlTextWriterAttribute。Onclick,第页。GetPostBackEventReference(this));//当按钮被点击时,需要发回服务器触发下面的OnClick事件。

输出。add attribute(HtmlTextWriterAttribute。样式,button style);
输出。RenderBeginTag(HtmlTextWriterTag。输入);//输出按钮
输出。RenderEndTag();
输出。RenderEndTag();

输出。RenderEndTag();
输出。RenderBeginTag(HtmlTextWriterTag。tr);
输出。add attribute(HtmlTextWriterAttribute。Colspan,“2”);
输出。RenderBeginTag(HtmlTextWriterTag。TD);
_日历。RenderControl(输出);//输出日历子控件
输出。RenderEndTag();
输出。RenderEndTag();
输出。RenderEndTag();
}

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

public void RaisePostBackEvent(string event argument)
{
OnClick(EventArgs。空);
}

protected virtual void onclick(eventargs e)
{
/当您单击“选择日期”按钮时,如果calendar子控件未显示,则会显示它,并且文本框的值将分配给calendar子控件
,如果(_ calendar . attributes[" display "]!= "")
{
_Calendar。SelectedDate = DateTime。解析(文本);
_日历。Style.Add("display "," ");
}
}

//复合控件中的日历控件日期更改事件

private _ calendar _ selection changed(object sender,eventargs e)
{
//当所选日期发生变化时,将所选日期赋给文本框并隐藏日历子控件
text = _ calendar . selected date . tostring();
_日历。Style.Add("display "," none ");
}
}
}


在上述代码中,应注意以下几点:

如果要重载该控件的某些属性,请在声明属性之前添加virtual关键字;

当页面输出该控件时(即在Render事件中),先定义子控件的样式或属性,再生成子控件;

隐藏calendar子控件时,建议不要使用Visible属性来显示/隐藏。使用Visible=false隐藏时,服务器不会向客户端发送日历控件HTML代码,会导致复合控件在空白中加载日历控件表空,影响页面的布局。因此,使用了style display=none设置来隐藏客户端中的calendar控件,但是HTML代码仍然存在于页面中;

四。结束语

编写服务器控件时,需要一定的HTML语言基础,还应该知道如何处理。NET程序。服务器封装了客户端的行为和逻辑判断,不需要开发者增加更多代码。当然,在某些地方使用服务器控件可以带来方便,但也增加了服务器的负载。有时候适当结合JavaScript,让一些代码在客户端运行,可以提高WEB应用的效率。

位律师回复
DABAN RP主题是一个优秀的主题,极致后台体验,无插件,集成会员系统
白度搜_经验知识百科全书 » 用VisualC#.NET编写服务器日期控件

0条评论

发表评论

提供最优质的资源集合

立即查看 了解详情