asp.net2.0的用户控件和自定义的差别
用户控件用.ascx文件表示,在"添加新项"中点击"vveb用户控件".它不是编译代码,编译随网页动态的进行
自定义控件在dll文件中表示,它是编译代码。在“新建项目”的模块中点击“web控件库”,
用户控件不会出现在工具箱中,而自定义控件会出现在工具箱中。
用户控件支持缓存,而自定义控件不支持缓存。
用户控件会对使用可视化设计的用户提供有限的支持,而自定义控件会提供全面的支持。
用户控件可以在一个应用程序中重用,但不能跨应用程序重用。
自定义用户就可以跨应用程序使用,它放在被称为全局程序集缓存的中央库中,以便那台服务器上的所有应用程序都可以使用它。
用户控件不能独立存在和使用,它要求用asp.net页面作为容器。
下面是一个login用户控件的示例
public partial class Login : System.Web.UI.UserControl
{
protected SqlConnection conn;
protected SqlCommand cmd;
protected SqlDataReader dr;
/// <summary>
/// Txtusername是用户控件的属性,要想在aspx访问它必须先封装起来为public才行
/// </summary>
public string Txtusername
{
get { return this.TextBox1.Text; }
set { this.TextBox1.Text = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click1(object sender, EventArgs e)
{
string strname = this.TextBox1.Text.Trim();
string strpwd = this.TextBox2.Text.Trim();
//根据指定的密码利用哈希算法转换成一个MD5的哈希密码
//this.Response.Write(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(strpwd, "MD5"));
conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DBuserConnectionString"].ToString());
conn.Open();
cmd = new SqlCommand("select * from userdetails where username=@username and userpwd=@userpwd", conn);//System.Web.Configuration.FormsAuthPasswordFormat.MD5
cmd.Parameters.Add(new SqlParameter("@username", strname));
//注意如果数据库里的密码是加密的话,在这里根据条件查询赋值前也得MD5加密才是
cmd.Parameters.Add(new SqlParameter("@userpwd", System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(strpwd, "MD5")));
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
//前进下一条记录
if (dr.Read())
{
//状态管理,在asp.net中默认的状态是用cookie保存的
//在用户每次登陆成功时就把用户保存到Cookie中,并用一个复选框来管理用户是否多长时间保存状态
HttpCookie cookie = new HttpCookie("username", strname);
if (this.CheckBox1.Checked)
{
//设置cookie的过期日期
cookie.Expires = DateTime.Now.AddMonths(1);
//响应后添加到cookies集合里
this.Response.Cookies.Add(cookie);
}
//过3秒后自动跳转页面,相当于html的mate标签
this.Response.AppendHeader("refresh", "3;url=DataListDemo1.aspx");
}
else
{
this.Response.Write("username or password are wrong!");
}
conn.Close();
}
}