日期:2012-04-19  浏览次数:20401 次

在DotNet中有用户自定义控件(.ascx)和服务器控件(程序代码)

WebControl 类提供所有 Web 服务器控件的公共属性、方法和事件。通过设置在此类中定义的属性,可以控制 Web 服务器控件的外观和行为。

例如在Community中DatePicker控件的实现

public class DatePicker : WebControl, INamingContainer {

DropDownList dropMonth;

DropDownList dropDay;

DropDownList dropYear;



public int Month {

get {

if (ViewState["Month"] == null)

return DateTime.Now.Month;

else

return (int)ViewState["Month"];

}

set { ViewState["Month"] = value; }

}



public int Day {

get {

if (ViewState["Day"] == null)

return DateTime.Now.Day;

else

return (int)ViewState["Day"];

}

set { ViewState["Day"] = value; }

}



public int Year {

get {

if (ViewState["Year"] == null)

return DateTime.Now.Year;

else

return (int)ViewState["Year"];

}

set {

ViewState["Year"] = value;

}

}



public DateTime Date {

get {

//确定服务器控件是否包含子控件。如果不包含,则创建子控件。

EnsureChildControls();



int _year = Int32.Parse(dropYear.SelectedItem.Value);

int _month = Int32.Parse(dropMonth.SelectedItem.Value);

int _day = Int32.Parse(dropDay.SelectedItem.Value);



if (_day > DateTime.DaysInMonth(_year, _month) )

throw new ArgumentException("Invalid date!");



return new DateTime

(

_year,

_month,

_day

);

}

set {

Month = value.Month;

Day = value.Day;

Year = value.Year;

}

}



/// <summary>

/// 通知使用基于合成的实现的服务器控件创建它们包含的任何子控件,以便为回发或呈现做准备。

/// 当开发复合服务器控件或模板服务器控件时,必须重写此方法。

/// </summary>

protected override void CreateChildControls() {

dropMonth = new DropDownList();

Controls.Add(dropMonth);



dropDay = new DropDownList();

Controls.Add(dropDay);



dropYear = new DropDownList();

Controls.Add(dropYear);



if (!Page.IsPostBack) {

// Get a DateTimeFormatInfo object

DateTimeFormatInfo objDateInfo = DateTimeFormatInfo.CurrentInfo;



// Display Months

for (int i=1;i<objDateInfo.MonthNames.Length;i++)

dropMonth.Items.Add(new ListItem(objDateInfo.GetMonthName(i), i.ToString()));



// Display Days