玩转C科技.NET

从学会做人开始认识这个世界!http://volnet.github.io

导航

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

源代码下载:       https://files.cnblogs.com/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月 >
31 1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31 1 2 3
4 5 6 7 8 9 10


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控件]


源代码下载:       https://files.cnblogs.com/volnet/WebAppUserControlTest.rar

posted on 2007-01-13 01:13  volnet(可以叫我大V)  阅读(2029)  评论(1编辑  收藏  举报

使用Live Messenger联系我
关闭