原文地址:ASP.NET用戶登陸和註冊的代碼做者:54黃二 using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Data.SqlClient; public partial class Login : System.Web.UI.Page { protected System.Data.SqlClient.SqlConnection Cn; protected System.Data.SqlClient.SqlCommand Cm; protected System.Data.SqlClient.SqlDataAdapter Da; protected System.Data.DataSet Ds; protected System.Data.SqlClient.SqlDataReader Dr; protected void Regist_Click(object sender, EventArgs e) { string str = ConfigurationSettings.AppSettings["strConnection"]; Cn = new SqlConnection(str); Cn.Open(); Cm = new SqlCommand("SELECT * FROM userlogin WHERE username='" + nametex.Text + "'", Cn); Dr = Cm.ExecuteReader(); if (Dr.Read())//若是存在相同用戶名 { Response.Write("<script>alert('用戶已被註冊');window.window.location.href='Login.aspx';</script>") ; Dr.Close(); } else { Dr.Close(); SqlCommand Cm2 = new SqlCommand("INSERT INTO userlogin (username,password,email,question,answer) VALUES ('" + nametex.Text + "','" + passwtex.Text + "','" + mailtex.Text + "','" + questex.Text + "','" + anstex.Text + "')", Cn); int i = Cm2.ExecuteNonQuery(); //message.InnerHtml = "註冊成功"; Response.Write("<script>alert('註冊成功');window.window.location.href='Login.aspx';</script>"); } Cn.Close(); } protected void Login_Click(object sender, EventArgs e) { if (us.Text!= null && pas.Text != null) { string str = ConfigurationSettings.AppSettings["strConnection"]; Cn = new SqlConnection(str); Cn.Open(); Cm = new SqlCommand("SELECT * FROM userlogin WHERE username='" + us.Text + "' AND password ='" + pas.Text + "'", Cn); Dr = Cm.ExecuteReader(); if (Dr.Read())//用戶名和密碼是否正確 { Session["username"] = us.Text; Session["password"] = pas.Text; //FormsAuthentication.SetAuthCookie(userTxt.Text, PersistCookie.Checked); // FormsAuthentication.RedirectFromLoginPage(userTxt.Text, PersistCookie.Checked); Response.Write("<script>alert('登錄成功');window.window.location.href='Login.aspx';</script>"); Dr.Close(); } else { //Dr.Close(); //message.InnerHtml = "用戶名或密碼錯誤!若是還未註冊,請先註冊!"; Response.Write("<script>alert('用戶名或密碼錯誤!若是還未註冊,請先註冊!');window.window.location.href='Login.aspx';</script>"); } Cn.Close(); } else { Response.Write("<script>alert('請輸入用戶名和密碼!');window.window.location.href='Login.aspx';</script>"); } } }