標籤:style class blog c code java
以前有大學有學過,但是沒學好,現在準備完全自己動手做一個網站,學習一下ASP.NET
做一個登入頁面,首先要有建立一個新的網站,添加Login.aspx,然後做出自己想要的DIV和CSS布局,
之後建立自己的資料庫,代碼如下:
USE [master] GOIF EXISTS(SELECT * FROM dbo.sysdatabases where dbid=DB_ID(‘MyStore‘)) DROP DATABASE MyStoreGOCREATE DATABASE [MyStore]GOUSE [MyStore] GOCREATE TABLE [VIP_USER]([User_Id] INT PRIMARY KEY IDENTITY,[User_Name] CHAR(50) NOT NULL,[User_Password] CHAR(50) NOT NULL)GO INSERT INTO [VIP_USER] VALUES(‘tangxuelong‘,‘[email protected]‘)
下一步就要準備連結資料庫了,首先在webconfig的connectString中寫入自己的連結字串,
然後項目添加一個類庫,DAL,DAL中添加DBhelper類,這時候給DBhelper添加System。configuration的引用
之後是代碼如下:
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Configuration;using System.Data;using System.Data.SqlClient;namespace DAL{ public class DBhelper { public SqlConnection Getcoon(){ string Sql = System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString(); //擷取連結字串 SqlConnection conn = new SqlConnection(Sql); return conn; } }}
給項目添加對DAL類庫的引用之後
下一步雙擊Login.aspx中的登入按鈕,給它添加click時間代碼,
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using DAL; //添加對DAL命名空間的引用using System.Data; using System.Data.SqlClient;namespace MyStore{ public partial class Login : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { string userName = "innite"; //初始化 string password = "innite"; DBhelper db = new DBhelper(); //對象執行個體化才能調用類中的public方法 SqlConnection conn = db.Getcoon(); if (conn.State.Equals(ConnectionState.Open))//判斷資料庫是否已被開啟 { conn.Close(); } conn.Open();//開啟資料庫連接 string sql = "select User_Name,User_Password from VIP_USER"; SqlCommand cmd = new SqlCommand(sql, conn); cmd.CommandType = CommandType.Text; try { SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { userName = reader[0].ToString(); password = reader[1].ToString(); } } catch (Exception msg) { Response.Write("<script>alert(" + msg + ");</script>"); } finally { conn.Close(); cmd.Dispose(); } if (ValidateUser(userName, password)) { Response.Redirect("~/Main.aspx"); } else { Response.Write("<script>alert(‘使用者名稱或密碼無效!請重新輸入!‘);</script>"); } } public Boolean ValidateUser(string UserName, string Password) //驗證使用者名稱和密碼 { if (UserName.Trim()!= TextBoxusername.Text.Trim()||Password.Trim()!=Textpassword.Text.Trim()) { return false; } else { return true; } } }}
F5運行,完成登入後跳轉到Main.aspx中。
完全菜鳥,不足之處很多,大神若有指教,感激不盡。