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();
}
}