您的位置:首页 > 编程语言 > ASP

[ASP.NET][实例]用户控件的设计与使用

2007-01-23 15:51 696 查看
源代码下载: http://www.cnblogs.com/Files/volnet/WebAppUserControlTest.rar

WebUserControl的创建和使用:
1、新建一个Web解决方案;

创建:
2、在菜单栏上点“项目”->“添加新项”->选择“Web用户控件”->默认名称“WebUserControl1.ascx”;
3、在“解决方案资源管理器”中找到“WebUserControl1.ascx”,在编辑器左下角点设计,切换到设计视图;
4、在“工具箱”中添加任意控件至WebUserControl1.ascx的设计视图;
例如:
a、本例中添加文本“用户控件测试”;
b、日历控件;
c、Label控件,Text属性为空;
d、Button,Text属性为“测试用户控件”;
5、为控件添加属性方法和事件:
a、添加公共方法以供外部调用:


public void Configure(Datetime date)






{


Calendar1.SelectedDate = date;


}

b、回到设计视图,双击Button控件,在其Click事件中添加方法:


protected void Button1_Click(object sender, EventArgs e)






{


Label1.Text = "测试成功!";


}

6、点“保存”,保存当前编辑的用户控件。

使用:
1、打开起始页Default.aspx;
2、在解决方案资源管理器中选中WebUserControl1.ascx,并拖动至Default.aspx的设计视图中;
用户控件测试
<2007年1月>
31123456
78910111213
14151617181920
21222324252627
28293031123
45678910
3、可以查看Default.aspx的“源”视图,可以看到:


〈uc1:WebUserControl1 id="WebUserControl1_1" runat="server">


〈/uc1:WebUserControl1>

uc1也就是UserControl的缩写,与<asp>标签的写法类似。
4、在Default.aspx.cs文件的Page_Load事件中添加加载日历当前选择的方法


protected void Page_Load(object sender, EventArgs e)






{


WebUserControl1_1.Configure(DateTime.Today);


}

测试:
1、按Ctrl+F5启动主页;
2、查看当前日期是否选中?选中?->OK;
3、点“测试用户控件”按钮,在Label1的位置能看到“测试成功!”的文字,说明控件已经设计成功了。

动态加载控件请参考:
[C#][SAMPLE]动态加载控件[PlaceHolder控件]

源代码下载: http://www.cnblogs.com/Files/volnet/WebAppUserControlTest.rar


http://www.cnblogs.com/volnet/archive/2007/01/13/619315.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: