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

强大的ASP.NET控件----用户控件对战自定义控件

2014-11-08 21:34 169 查看
用户控件:给特定程序使用
举例:用户控件之登陆
在VS中创建程序,如下

打开userControl.ascx,拖入如下控件:



打开UserControl.ascx下的UserControl.ascx.cs,写入如下代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace UserControl
{
publicpartial class UserControl : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{

}
publicstring txtUserName//属性1:用户名
{
set
{
this.txtName.Text = value;
}
get
{
return this.txtName.Text;
}
}

publicstring txtUserPwd//属性2:密码
{
set
{
this.txtPwd.Text = value;
}
get
{
return this.txtPwd.Text;
}
}
//控件事件
protected void btnLogin_Click(object sender, EventArgs e)
{
if((txtUserName == "liuying") && (txtUserPwd =="liuying"))
{
Response.Write("登陆成功");
}
else
{
Response.Write("登陆失败");
}
}
}
}



将WebForm1设为启动窗体,然后打开WebForm1.aspx,切换到设计窗口,将用户控件,拖入页面中,Ctrl+F5,启动程序,在文本框中输入字符串,点击登陆,界面会提示登陆成功或失败。



给用户控件的属性赋值,方法很多,以上在文本框中输入是一种方法,还有一种方法是在WebForm1的用户界面代码窗体中直接赋值
 <uc1:UserControl ID="loginControl" txtUserName="liuying" txtUserPwd="liuying" runat="server" />

还有在WebForm1的用户界面设计窗体中,右击用户控件,选择属性



 
自定义控件:自定义控件是全局的,只要设定好了,所有使用此Visual Studio的用户均可以使用
举例:命名空间的引用是不是很麻烦,而且我们常常会忘记在特定环境中应该引用哪些类库,例如D层的命名空间



不论自定义控件还是用户控件,都会给我们的编程之路带来方便,学会使用两者不难,善用很难!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐