自己建立的數據庫:UserInfo
表明:UserInfo
作爲一個開發者,我們清楚大多數的程序都有一個登陸與處理忘記密碼等等功能的模塊。
現在,使用 Visual Studio 2005,設計登陸頁面變得非常簡單因爲 VS 2005 開發環境的工具箱有了內建的登陸分組,這個分組有各種跟登陸功能相關的控件。
圖1.1:工具箱中的登陸分組
圖1.2:登陸分組的所有控件
下面我們將看到在 C#.Net 中如何使用 Login 控件。接下來的代碼將會解釋如果使用數據庫來驗證用戶身份。
第一步:- 在拖拽 Login 控件到頁面上這樣在設計視圖中它會看起來像一個登陸頁面。
圖1.3:設計視圖下的 Login 控件
第二步:一旦 UI 設置好了就該轉到代碼部分來看如何給控件寫代碼了。
爲這個控件編寫響應代碼,我們首先要處理 Login1_Authenticate 事件。
雙擊 Login 控件將會生成如下代碼:
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
bool Authenticated = false;
Authenticated = SiteLevelCustomAuthenticationMethod(Login1.UserName, Login1.Password);
e.Authenticated = Authenticated;
if (Authenticated == true)
{
Response.Redirect("Home.aspx");
}
}
private bool SiteLevelCustomAuthenticationMethod(string UserName, string Password)
{
bool boolReturnValue = false;
// Insert code that implements a site-specific custom
// authentication method here.
// This example implementation always returns false.
string strConnection = "server=.;database=UserInfo;uid=sa;pwd=sa;";
SqlConnection Connection = new SqlConnection(strConnection);
String strSQL = "Select * From UserInfo";
SqlCommand command =new SqlCommand(strSQL, Connection);
SqlDataReader Dr;
Connection.Open();
Dr=command.ExecuteReader();
while (Dr.Read())
{
if ((UserName == Dr["name"].ToString()) & (Password == Dr["Password"].ToString()))
{
boolReturnValue = true;
}
}
Dr.Close();
return boolReturnValue;
}
Login 控件有一個名爲 FailureText 的屬性可以用來設置自己的登陸失敗提示信息。
圖1.4:自定義錯誤信息
一旦通過了身份驗證,程序將根據 DestinationPageUrl 屬性轉向首頁。DestinationPageUrl 是 Login 控件用來設置身份驗證成功之後轉向的屬性。如果驗證失敗將會給出錯誤信息提示。下面是一個用戶自定義 FailureText 屬性來設置出錯提示信息截圖。
圖1.5:登陸出錯
關於內建的驗證機制:Login 控件有一個內建的驗證機制作爲屬性提供給開發者。當您在設計視圖拖拽控件您將會發現 username 與 password 文本框被標記了 * 號 - 意味着這些部分是必須要填寫的。
本文來自CSDN博客,轉載請標明出處:http://blog.csdn.net/wei_liasp/archive/2009/11/26/4879126.aspx