學生信息管理系統 C# + SQL

開發工具:Microsoft SQL Serever 2017 / Microsoft Visual studio 2019
開發語言:SQL / C#

一、需求分析

根據對學生信息管理的需要,設計並實現“學生信息管理系統”,該程序主要有由註冊、學生登錄和管理員登錄組成,在登錄之前應先註冊,學生登錄可以完成查詢“個人信息”、“成績信息”、“選課信息”、“修改密碼”的操作,管理員登錄可以完成對“學生”、“課程”、“學生-課程”、“登錄日誌”、“個人信息”、“修改密碼”的操作。
註冊登錄:註冊時需要補充相應的信息如:用戶名、密碼、學號、工號、聯繫方式、出生日期、身份、照片。註冊完可直接登錄,登錄時需要輸入用戶名、密碼、驗證碼(可以更換驗證碼)。

學生登錄:主要對用戶的個人信息、成績信息和選課信息進行查詢。
管理員登錄:主要對學生的個人信息、課程基本信息、學生成績信息進行增、刪、改、查。

二、總體設計和詳細設計

2.1 總體功能設計
在這裏插入圖片描述

圖1 總體功能設計

根據圖1的總體功能設計,各模塊功能需求如下:
1、註冊:註冊學生身份或管理員身份,需要填寫一些信息:用戶名、密碼(加密存儲)、學號、工號、聯繫方式、出生日期、身份、照片。註冊完可直接登錄。
2、學生登錄:可以查詢個人信息、成績信息、選課信息,還可以根據自己的用戶名修改登錄時的密碼。
個人信息包括學號、姓名、性別、聯繫方式、出生日期、年齡、專業和照片。
成績信息可以查看個人的所有課程的成績以及平均成績和不及格成績的信息。
3、管理員登錄:完成對學生表、課程表和成績的增刪改查操作,查看登錄日誌、個人信息,根據用戶名修改登陸密碼。
其中,學生表的增加要求姓名唯一,對性別和年齡加以限制,性別必須輸入爲“男”或“女”,年齡必須爲大於零的整數,還要求學生的學號不可重複;刪除時要求選擇一整行進行刪除,如果該學生已經選課,則提示該學而生無法刪除;修改時可以根據學號修改姓名、性別、年齡、系別;查找時可以根據學號和姓名單獨查詢,也可以根據性別、系別、年齡的任意組合進行查詢。
課程表的增加要求課程號唯一、先行課的選擇必須是已經存在的課程號;刪除時選擇一整行刪除,如果已經有學生選課,則提示無法刪除;修改時可以根據課程號修課程名、先行課和學分,也可以根據課程名修改先行課和學分;查找時可以根據課程號查找,也可以根據課程名、先行課和學分的任意組合查找。
學生-課程表完成對學生成績的操作,增加時學號和課程號必須是已經存在的;刪除時選中一整行刪除;修改時根據學號和課程號修改成績;查找時可以根據學號、課程號、成績的任意組合紀念性查找,也可以查找某門課程在某個分數段的學生成績信息。
登錄日誌可以查看學生和管理員的登錄和註冊的時間以及操作記錄。
個人信息包括:工號、姓名、性別、聯繫方式、出生日期、工資、職稱和照片的信息。

2.2 概念模型:E-R圖
通過需求分析,可以得到學生、課程、管理員、註冊、日誌實體,對實體之間的分析可得到如下的E-R圖。
1、系統總體E-R圖
在這裏插入圖片描述

圖2-1 系統總體E-R圖

2、實體圖
學生實體屬性包括學號、姓名、性別、年齡、系別。學生實體圖如圖2-2所示。
在這裏插入圖片描述

圖2-2 學生實體圖

管理員實體屬性包括工號、姓名、性別、工資、職稱。管理員實體圖如圖2-3所示。
在這裏插入圖片描述

圖2-3 管理員實體圖

課程實體屬性包括課程號、課程名、先行課、學分。課程實體圖如圖2-4所示。
在這裏插入圖片描述

圖2-4 課程實體圖

註冊實體屬性包括用戶名、密碼、學號/工號、聯繫方式、出生日期、身份、照片。註冊實體圖如圖2-5所示。
在這裏插入圖片描述

圖2-5 註冊實體圖

日誌實體屬性包括用戶名、時間、操作。日誌實體圖如圖2-6所示。

在這裏插入圖片描述

圖2-6 日誌實體圖

2.3 邏輯模型:基本表
以下爲各數據表的屬性字段說明:
1、學生表(Student),記錄學生的基本信息。通過分析表中各屬性字段得到的具體數據類型如表3-1.

表3-1 學生表
列名 說明 數據類型 約束
Sno 學號 CHAR(9) 主碼
Sname 姓名 CHAR(20) 唯一UNIQUE
Ssex 性別 CHAR(2) NOT NULL,取“男”或“女”
Sage 年齡 SMALLINT NOT NULL,大於0
Sdept 系別 CHAR(20)

2、課程表(Course),記錄課程信息。通過分析表中各屬性字段得到的具體數據類型如表3-2.

表3-2 課程表
列名 說明 數據類型 約束
Cno 課程號 CHAR(4) 主碼
Cname 課程名 CHAR(40) NOT NULL
Cpno 先行課 CHAR(4) Course表的外碼
Ccredit 學分 SMALLINT NOT NULL

3、學生-課程表(SC),記錄學生成績信息。通過分析表中各屬性字段得到的具體數據類型如表3-3.

表3-3 學生-課程表
列名 說明 數據類型 約束
Sno 學號 CHAR(9) Student表的外碼
Cno 課程號 CHAR(4) Course表的外碼
Grade 成績 SMALLINT
Sno和Cno共同構成主碼

4、管理員表(Admin),記錄管理員的個人信息。通過分析表中各屬性字段得到的具體數據類型如表3-4.

表3-4 管理員表
列名 說明 數據類型 約束
Ano 工號 CHAR(9) 主碼
Aname 姓名 CHAR(20) NOT NULL,唯一 UNIQUE
Asex 性別 CHAR(2) NOT NULL,取“男”或“女”
Asalary 工資 CHAR(10) NOT NULL
Atitle 職稱 CHAR(10)

5、用戶註冊表(SysUser),記錄用戶登錄時的信息。通過分析表中各屬性字段得到的具體數據類型如表3-5.

表3-5 用戶註冊表
列名 說明 數據類型 約束
UserID 用戶名 NCHAR(20) 主碼
UserPassWord 密碼 NCHAR(32) NOT NULL
UserSchoolID 學號/工號 NCHAR(20) NOT NULL
UserMobile 聯繫方式 NCHAR(11) NOT NULL
UserBirthday 出生日期 datatime
UserIdentity 身份 NCHAR(20) NOT NULL
UserPhoto 照片 image

6、用戶登錄記錄表(SysLog),記錄用戶的登錄和註冊日誌。通過分析表中各屬性字段得到的具體數據類型如表3-6.

表3-6 用戶登錄記錄表
列名 說明 數據類型 約束
UserID 用戶名 NCHAR(20)
DataAndTime 時間 datatime
UserOperation 操作 NCHAR(200)

三、系統實現

數據庫建表準備:


CREATE TABLE SysUser          
 (	
 UserID NCHAR(20) PRIMARY KEY,                          
 UserPassWord NCHAR(32) NOT NULL,             
 UserSchoolID NCHAR(20) NOT NULL,
 UserMobile NCHAR(11) NOT NULL,
 UserBirthday datetime,
 UserIdentity NCHAR(20) NOT NULL,
 UserPhoto image
 ); 


 CREATE TABLE SysLog          
 (	
 UserID NCHAR(20) ,                          
 DateAndTime datetime,
 UserOperation NCHAR(200)
 ); 

CREATE TABLE Student          
 (	
 Sno CHAR(9) PRIMARY KEY,        /* 列級完整性約束條件,Sno是主碼*/                  
 Sname CHAR(20) UNIQUE,        
 Ssex CHAR(2) NOT NULL,check (Ssex in ('男','女')),
 Sage SMALLINT NOT NULL,check (Sage>0),
 Sdept CHAR(20)
 ); 

CREATE TABLE  Course
 (	
 Cno CHAR(4) PRIMARY KEY,
 Cname CHAR(40) NOT NULL,            
 Cpno CHAR(4),               	                      
 Ccredit SMALLINT NOT NULL,
 FOREIGN KEY (Cpno) REFERENCES  Course(Cno) 
 ); 

CREATE TABLE  SC
 (
 Sno CHAR(9), 
 Cno CHAR(4),  
 Grade SMALLINT,
 PRIMARY KEY (Sno,Cno),                     /* 主碼由兩個屬性構成,必須作爲表級完整性進行定義*/
 FOREIGN KEY (Sno) REFERENCES Student(Sno),  /* 表級完整性約束條件,Sno是外碼,被參照表是Student */
 FOREIGN KEY (Cno)REFERENCES Course(Cno)     /* 表級完整性約束條件, Cno是外碼,被參照表是Course*/
 ); 

INSERT  INTO  SysUser VALUES ('admin','123','000','13812345678',1999-1-1,'0',NULL);

INSERT  INTO  Student (Sno,Sname,Ssex,Sdept,Sage) VALUES ('201215121','李勇','男','CS',20);
INSERT  INTO  Student (Sno,Sname,Ssex,Sdept,Sage) VALUES ('201215122','劉晨','女','CS',19);
INSERT  INTO  Student (Sno,Sname,Ssex,Sdept,Sage) VALUES ('201215123','王敏','女','MA',18);
INSERT  INTO  Student (Sno,Sname,Ssex,Sdept,Sage) VALUES ('201215125','張立','男','IS',19);
INSERT  INTO  Student (Sno,Sname,Ssex,Sdept,Sage) VALUES ('201215128','陳冬','男','IS',20);
INSERT  INTO  Student (Sno,Sname,Ssex,Sdept,Sage) VALUES ('201215129','李麗','女','IS',20);
INSERT  INTO  Student (Sno,Sname,Ssex,Sdept,Sage) VALUES ('201215126','陳霞','男','MA',19);

SELECT * FROM Student

INSERT  INTO Course(Cno,Cname,Cpno,Ccredit)	VALUES ('1','數據庫',NULL,4);
INSERT  INTO Course(Cno,Cname,Cpno,Ccredit)	VALUES ('2','數學',NULL,4);
INSERT  INTO Course(Cno,Cname,Cpno,Ccredit)	VALUES ('3','信息系統',NULL,4);
INSERT  INTO Course(Cno,Cname,Cpno,Ccredit)	VALUES ('4','操作系統',NULL,4);
INSERT  INTO Course(Cno,Cname,Cpno,Ccredit)	VALUES ('5','數據結構',NULL,4);
INSERT  INTO Course(Cno,Cname,Cpno,Ccredit)	VALUES ('6','數據處理',NULL,4);
INSERT  INTO Course(Cno,Cname,Cpno,Ccredit)	VALUES ('7','Pascal語言',NULL,4);

UPDATE Course SET Cpno = '5' WHERE Cno = '1' 
UPDATE Course SET Cpno = '1' WHERE Cno = '3' 
UPDATE Course SET Cpno = '6' WHERE Cno = '4' 
UPDATE Course SET Cpno = '7' WHERE Cno = '5' 
UPDATE Course SET Cpno = '6' WHERE Cno = '7' 

SELECT * FROM Course

INSERT  INTO SC(Sno,Cno,Grade) VALUES ('201215121 ','1',92);
INSERT  INTO SC(Sno,Cno,Grade) VALUES ('201215121 ','2',85);
INSERT  INTO SC(Sno,Cno,Grade) VALUES ('201215121 ','3',88);
INSERT  INTO SC(Sno,Cno,Grade) VALUES ('201215122 ','2',90);
INSERT  INTO SC(Sno,Cno,Grade) VALUES ('201215122 ','3',80);
INSERT  INTO SC(Sno,Cno,Grade) VALUES ('201215121 ','4',56);
INSERT  INTO SC(Sno,Cno,Grade) VALUES ('201215125 ','1',85);
SELECT * FROM SC

CREATE TABLE Admin(Ano char (9) PRIMARY KEY,
		  Aname char(20) NOT NULL,
		  Asex char (2) NOT NULL,check (Asex in ('男','女')),
		  Asalary char(10) NOT NULL,
		  Atitle char(10));

INSERT  INTO Admin(Ano,Aname,Asex,Asalary,Atitle) VALUES ('1','王琦','女',5000,'副教授');
INSERT  INTO Admin(Ano,Aname,Asex,Asalary,Atitle) VALUES ('2','陳宇','男',5500,'教授');
INSERT  INTO Admin(Ano,Aname,Asex,Asalary,Atitle) VALUES ('3','劉寧','女',4500,'講師');
INSERT  INTO Admin(Ano,Aname,Asex,Asalary,Atitle) VALUES ('4','王晨','女',6000,'教授');
INSERT  INTO Admin(Ano,Aname,Asex,Asalary,Atitle) VALUES ('5','韓新','女',4000,'講師');
INSERT  INTO Admin(Ano,Aname,Asex,Asalary,Atitle) VALUES ('6','王韓','女',5400,'教學祕書');

select *
from Admin

建立觸發器:

IF(OBJECT_ID('regist_recorder') is not null)        -- 判斷名爲 regist_recorder 的觸發器是否存在
DROP TRIGGER regist_recorder        -- 刪除觸發器
GO

CREATE TRIGGER regist_recorder
ON SysUser  	         
AFTER
INSERT
AS 
	declare @UserName    nchar(20)
	declare @DateTime    datetime
	declare @UserOperation nchar(200)

	select @UserName = system_user
	select @DateTime = CONVERT(datetime,GETDATE(),120) 

	declare @op varchar(10)
	select @op=case when exists(select 1 from inserted) and exists(select 1 from deleted)
                   then 'Update'
                   when exists(select 1 from inserted) and not exists(select 1 from deleted)
                   then 'Insert'
                   when not exists(select 1 from inserted) and exists(select 1 from deleted)
                   then 'Delete' end
                   
	
	select @UserOperation = @op
	

	INSERT INTO SysLog(UserID,DateAndTime,UserOperation)
	VALUES (@UserName,@DateTime,@UserOperation)

  • 註冊界面:輸入信息選擇身份註冊。
    用戶名和密碼必須爲“至少有數字、大寫字母、小寫字母各一個。最少3個字符、最長20個字符!”,否則會提示。
    在這裏插入圖片描述
    MD5加密
 public Byte[] mybyte = new byte[0];

        public static string EncryptWithMD5(string source)  //MD5加密
        {
            byte[] sor = Encoding.UTF8.GetBytes(source);
            MD5 md5 = MD5.Create();
            byte[] result = md5.ComputeHash(sor);
            StringBuilder strbul = new StringBuilder(40);
            for (int i = 0; i < result.Length; i++)
            {
                strbul.Append(result[i].ToString("x2"));//加密結果"x2"結果爲32位,"x3"結果爲48位,"x4"結果爲64位
            }
            return strbul.ToString();
        }

上傳照片

 private void buttonphoto_Click(object sender, EventArgs e)
        {
            //打開瀏覽圖片對話框
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.ShowDialog();
            string picturePath = openFileDialog.FileName;//獲取圖片路徑
            //文件的名稱,每次必須更換圖片的名稱,這裏很爲不便
            //創建FileStream對象
            FileStream fs = new FileStream(picturePath, FileMode.Open, FileAccess.Read);
            //聲明Byte數組
            mybyte = new byte[fs.Length];
            //讀取數據
            fs.Read(mybyte, 0, mybyte.Length);
            pictureBox1.Image = Image.FromStream(fs);
            fs.Close();
        }

確定按鈕

private void buttonok_Click(object sender, EventArgs e)
        {
            try
            {
                string connString = "Data Source =.; Initial Catalog = School;  Persist Security Info = True;User ID = sa; Password = 123";//數據庫連接字符串
                SqlConnection connection = new SqlConnection(connString);//創建connection對象
                string sql = "insert into SysUser (UserID,   UserPassWord ,   UserSchoolID, UserMobile, UserBirthday , UserIdentity , UserPhoto ) " +
                                                        "values (@userid, @userpassword,@userschoolid,@usermobile,@userbirthday,@useridentity,@userphoto)";
                SqlCommand command = new SqlCommand(sql, connection);

                SqlParameter sqlParameter = new SqlParameter("@userid", textBoxusername.Text);
                command.Parameters.Add(sqlParameter);
                sqlParameter = new SqlParameter("@userpassword", EncryptWithMD5(textBoxpassword.Text));
                command.Parameters.Add(sqlParameter);
                sqlParameter = new SqlParameter("@userschoolid", textBoxid.Text);
                command.Parameters.Add(sqlParameter);
                sqlParameter = new SqlParameter("@usermobile", textBoxmobile.Text);
                command.Parameters.Add(sqlParameter);
                sqlParameter = new SqlParameter("@userbirthday", dateTimePickerbirth.Value);
                command.Parameters.Add(sqlParameter);
                sqlParameter = new SqlParameter("@useridentity", comboBoxidentity.Text);
                command.Parameters.Add(sqlParameter);
                sqlParameter = new SqlParameter("@userphoto", SqlDbType.VarBinary, mybyte.Length, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, mybyte);
                command.Parameters.Add(sqlParameter);

                //打開數據庫連接
                connection.Open();
                command.ExecuteNonQuery();
                connection.Close();
                MessageBox.Show("註冊成功!");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            this.Close();
        }

用戶名和密碼的格式限制。點擊用戶名和密碼的文本框,點擊屬性/事件裏面的Leave。

  private void textBoxusername_Leave(object sender, EventArgs e)
        {
            if (textBoxusername.Text.Trim() != "")
            {
                //使用regex(正則表達式)進行格式設置 至少有數字、大寫字母、小寫字母各一個。最少3個字符、最長20個字符。
                Regex regex = new Regex(@"(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).{3,20}");

                if (regex.IsMatch(textBoxusername.Text))//判斷格式是否符合要求
                {
                    //MessageBox.Show("輸入用戶名格式正確!");
                }
                else
                {
                    MessageBox.Show("至少有數字、大寫字母、小寫字母各一個。最少3個字符、最長20個字符!");
                    textBoxusername.Focus();
                }
            }
            else
            {
                MessageBox.Show("用戶名不能爲空!");
            }
        }
    
        private void button1_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void textBoxpassword_Leave_1(object sender, EventArgs e)
        {
            if (textBoxpassword.Text.Trim() != "")
            {
                //使用regex(正則表達式)進行格式設置 至少有數字、大寫字母、小寫字母各一個。最少3個字符、最長20個字符。
                Regex regex = new Regex(@"(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).{3,20}");

                if (regex.IsMatch(textBoxpassword.Text))//判斷格式是否符合要求
                {
                    //MessageBox.Show("輸入密碼格式正確!");
                }
                else
                {
                    MessageBox.Show("至少有數字、大寫字母、小寫字母各一個。最少3個字符、最長20個字符!");
                    textBoxpassword.Focus();
                }
            }
            else
            {
                MessageBox.Show("密碼不能爲空!");
            }
        }
  • 登錄界面:輸入用戶名、密碼、驗證碼(可以更改)和選擇正確的身份即可登錄。

學生登錄
可以通過點擊窗口的,將StartPosition改爲CenterScreen,,將窗體顯示在屏幕中間。在這裏插入圖片描述
獲取驗證碼:

 public void ShowCode()   //驗證碼取值
        {
            labelcode.Text = "";
            //隨機實例化 
            Random ran = new Random();
            int number;
            char code1;
            //取五個數 
            for (int i = 0; i < 5; i++)
            {
                number = ran.Next();
                if (number % 2 == 0)
                    code1 = (char)('1' + (char)(number % 9));
                //由於O與0經常混淆,所以數字從1-9,大寫英文字母A-Z
                else
                    code1 = (char)('A' + (char)(number % 26)); //轉化爲字符 
                this.code += code1.ToString();
            }
            labelcode.Text = code;
        }

        public string code;

        private void Form1_Load(object sender, EventArgs e)
        {
            ShowCode();
        }
          private void linkLabelchange_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)//更改驗證碼
        {
            this.code = "";
            ShowCode();
        }

登錄按鈕

 static String name;
 string identity;
        public string Get()
        {
            return name;
        }
        private void buttonlogin_Click(object sender, EventArgs e)
        {
            string username = textBoxusername.Text.Trim();  //取出賬號
            string password = EncryptWithMD5(textBoxpassword.Text.Trim());  //取出密碼並加密        
            name = username;          
            if (radioButtonadmin.Checked)
            {
                identity = radioButtonadmin.Text;
            }
            else if (radioButtonstudent.Checked)
            {
                identity = radioButtonstudent.Text;
            }
            string myConnString = "Data Source =.; Initial Catalog = School;  Persist Security Info = True;User ID = sa; Password = 123";
            SqlConnection sqlConnection = new SqlConnection(myConnString);  //實例化連接對象
            sqlConnection.Open();         
            string sql = "select UserID,UserPassword,UserIdentity  from SysUser where UserID = '" + username + "' and UserPassword = '" + password + "' and UserIdentity='"+identity+"'";                                            //編寫SQL命令
            SqlCommand sqlCommand = new SqlCommand(sql, sqlConnection);

            SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();

            if (sqlDataReader.HasRows && textBoxcode.Text == code && radioButtonstudent.Checked)//學生成功登錄
            {            
                    MessageBox.Show("歡迎使用!");             //登錄成功
                    this.Hide();
                    StudentMain studentmain = new StudentMain();
                    studentmain.ShowDialog();                                                                  
            }
            if (sqlDataReader.HasRows && textBoxcode.Text == code && radioButtonadmin.Checked)//管理員成功登錄
            {
                MessageBox.Show("歡迎使用!");  
                this.Hide();           //登錄成功
                AdminMain adminmain = new AdminMain();
                adminmain.ShowDialog();               
            }                  
            if (textBoxcode.Text != code)       //驗證碼輸入錯誤,登錄失敗
            {
                MessageBox.Show("驗證碼錯誤!");
                return;
            }
            if (!sqlDataReader.HasRows)         //用戶名或密碼錯誤,登錄失敗
            {
                MessageBox.Show("密碼錯誤或該用戶不存在!");
                return;
            }
            if (!radioButtonstudent.Checked && !radioButtonadmin.Checked)        //未選擇身份
            {
                MessageBox.Show("請選擇登錄身份!");
                return;
            }
            sqlDataReader.Close();
            sql = "insert into SysLog values ( '" + username + "' , '" + DateTime.Now + "' , '" + "Login" + "')";                                            //編寫SQL命令
            sqlCommand = new SqlCommand(sql, sqlConnection);
            sqlCommand.ExecuteNonQuery();
            sqlConnection.Close();
        }

MD5加密

 public static string EncryptWithMD5(string source)      //MD5加密
        {
            byte[] sor = Encoding.UTF8.GetBytes(source);
            MD5 md5 = MD5.Create();
            byte[] result = md5.ComputeHash(sor);
            StringBuilder strbul = new StringBuilder(40);
            for (int i = 0; i < result.Length; i++)
            {
                strbul.Append(result[i].ToString("x2"));//加密結果"x2"結果爲32位,"x3"結果爲48位,"x4"結果爲64位
            }
            return strbul.ToString();
        }

進入下一個窗體,退出按鈕

 private void linkLabelregister_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            this.Hide();
            Register register = new Register();
            register.ShowDialog();           
        }
     
        private void buttonclose_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
  • 選擇要進行的操作:
    在這裏插入圖片描述
    點擊顯示下一個窗體
 private void buttonclose_Click(object sender, EventArgs e)//關閉
        {
            this.Close();
            Form1 m = new Form1();
            m.Show();
        }

        private void buttonpassword_Click(object sender, EventArgs e)//修改密碼
        {
            this.Hide();
            Student_password spw = new Student_password();
            spw.ShowDialog(); 
        }

        private void buttoninfo_Click(object sender, EventArgs e)//個人信息
        { 
            this.Hide();
            Student_info studentinfo = new Student_info();
            studentinfo.ShowDialog();          
        }

        private void buttongrade_Click(object sender, EventArgs e)//成績
        {  
            this.Hide();
            Student_grade studentgrade = new Student_grade();
            studentgrade.ShowDialog();         
        }

        private void buttoncourse_Click(object sender, EventArgs e)//課程
        {
            this.Hide();
            Student_Course student_course = new Student_Course();
            student_course.ShowDialog();           
        }

        private void button1_Click(object sender, EventArgs e)//退出
        {
            Application.Exit();            
        }

個人信息顯示:
在這裏插入圖片描述
返回上一個窗體,退出

 private void buttonselect_Click(object sender, EventArgs e)
        {
            this.Close();
            StudentMain s = new StudentMain();
            s.Show();
        }
private void button1_Click(object sender, EventArgs e)
      {
            Application.Exit();
      }

直接顯示個人信息

  private void Student_info_Load(object sender, EventArgs e)
        {
            try
            {
                Form1 m = new Form1();
                string select_name = m.Get();
                string connString = "Data Source=.;Initial Catalog=School;Persist Security Info=True;User ID=sa;Password=123";//數據庫連接字符串
                SqlConnection connection = new SqlConnection(connString);//創建connection對象              
                connection.Open(); //打開數據庫連接

                //顯示信息
                //在顯示出生日期,注意DataTime格式的轉換,以及完成查詢後的標籤內容的轉換                
                string select_a = "select Sno,Sname,Ssex,UserMobile,UserBirthday,Sage,Sdept from Student,SysUser where Student.Sno=SysUser.UserSchoolID and UserID='" + select_name + "'";
                SqlCommand cmd = new SqlCommand(select_a, connection); 
                SqlDataReader dr = cmd.ExecuteReader();//讀取數據
                dr.Read();
                if (dr.HasRows)
                {
                    labelsno.Text=dr[0].ToString();
                    labelsname.Text = dr[1].ToString();
                    labelssex.Text = dr[2].ToString();
                    labelsphone.Text = dr[3].ToString();
                  //  labelsbirth.Text = dr[4].ToString();
                    labelsbirth.Text = Convert.ToString(dr.GetDateTime(4).ToShortDateString());
                    labelsage.Text = dr[5].ToString();
                    labelsdept.Text = dr[6].ToString();                   
                }
                else { MessageBox.Show("您的信息還未錄入!"); }
                dr.Close();

                //顯示圖片,如果圖片顯示不全,將pictureBox的SizeMode改爲Zoom,圖片的長寬比例不變
                string sql = "select UserPhoto from SysUser where UserID = '" + select_name + "'";
                SqlCommand command = new SqlCommand(sql, connection);//創建SqlCommand對象
                //創建DataAdapter對象
                SqlDataAdapter dataAdapter = new SqlDataAdapter(command);
                //創建DataSet對象
                DataSet dataSet = new DataSet();
                dataAdapter.Fill(dataSet, "SysUser");
                int c = dataSet.Tables["SysUser"].Rows.Count;
                if (c > 0)
                {
                    Byte[] mybyte = new byte[0];
                    mybyte = (Byte[])(dataSet.Tables["SysUser"].Rows[c - 1]["UserPhoto"]);
                    MemoryStream ms = new MemoryStream(mybyte);
                    pictureBox1.Image = Image.FromStream(ms);
                }
                else
                    pictureBox1.Image = null;
                connection.Close();
            }
            catch
            {
                MessageBox.Show("顯示信息失敗!");
            }
        }

成績信息顯示:
在這裏插入圖片描述

窗口直接顯示成績

 String conn = "Data Source =.; Initial Catalog = School;  Persist Security Info = True;User ID = sa; Password = 123";
        static Form1 m = new Form1();
        static string select_name = m.Get();
        private void Student_grade_Load(object sender, EventArgs e)
        {
            SqlConnection sqlconnection = new SqlConnection(conn);//實例化連接對象
            try
            {
                sqlconnection.Open();
                string select_by_sno = "select SC.Sno,Sname,SC.Cno,Cname,Grade from Student,SC,Course,SysUser where Student.Sno=SC.Sno and Course.Cno=SC.Cno and SC.Sno=SysUser.UserSchoolID and UserID='" + select_name + "'";
                SqlCommand sqlcommand = new SqlCommand(select_by_sno, sqlconnection);
                SqlDataReader sqldatareader = sqlcommand.ExecuteReader();
                BindingSource bindingsource = new BindingSource();
                bindingsource.DataSource = sqldatareader;
                dataGridView1.DataSource = bindingsource;
            }
            catch
            {
                MessageBox.Show("查詢語句有誤,請認真檢查SQL語句");
            }
            finally
            {
                sqlconnection.Close();
            }
            // TODO: 這行代碼將數據加載到表“schoolDataSet5.SC”中。您可以根據需要移動或刪除它。
            this.sCTableAdapter.Fill(this.schoolDataSet5.SC);
        }
     

平均成績
在這裏插入圖片描述
查詢平均成績

 private void buttonavegrade_Click(object sender, EventArgs e)//查詢平均成績
        {       
            SqlConnection sqlconnection = new SqlConnection(conn);//實例化連接對象
            try
            {
                sqlconnection.Open();
                string select_avggrade = "select AVG(Grade) from SC,SysUser where  SC.Sno=SysUser.UserSchoolID and UserID='" + select_name + "'";               
                SqlCommand sqlcommand = new SqlCommand(select_avggrade, sqlconnection);
                SqlDataReader sqldatareader = sqlcommand.ExecuteReader();
                BindingSource bindingsource = new BindingSource();
                bindingsource.DataSource = sqldatareader;
                dataGridView1.DataSource = bindingsource;
            }
            catch
            {
                MessageBox.Show("查詢語句有誤,請認真檢查SQL語句");
            }
            finally
            {
                sqlconnection.Close();
            }
        }

不及格成績
在這裏插入圖片描述
查詢不及格成績

 private void buttonnograde_Click(object sender, EventArgs e)//查詢不及格成績信息
        {
            SqlConnection sqlconnection = new SqlConnection(conn);//實例化連接對象
            try
            {
                sqlconnection.Open();
                string select_nograde =" select Sno,SC.Cno,Cname,Grade from SC,Course,SysUser where SC.Cno=Course.Cno and SC.Sno = SysUser.UserSchoolID and Grade<60 and UserID = '" + select_name + "'";
                SqlCommand sqlcommand = new SqlCommand(select_nograde, sqlconnection);
                SqlDataReader sqldatareader = sqlcommand.ExecuteReader();
                BindingSource bindingsource = new BindingSource();
                bindingsource.DataSource = sqldatareader;
                dataGridView1.DataSource = bindingsource;
                if (dataGridView1.DataSource is null)
                {
                    string nullgrade = "wiekof";
                    SqlCommand sqlcommand1 = new SqlCommand(nullgrade, sqlconnection);
                    SqlDataReader sqldatareader1 = sqlcommand.ExecuteReader();
                    BindingSource bindingsource1= new BindingSource();
                    bindingsource.DataSource = sqldatareader1;
                    dataGridView1.DataSource = bindingsource1;
                }
            }
            catch
            {             
                MessageBox.Show("查詢語句有誤,請認真檢查SQL語句");
            }
            finally
            {
                sqlconnection.Close();
            }
            this.sCTableAdapter.Fill(this.schoolDataSet5.SC);
        }

選課信息顯示
在這裏插入圖片描述
窗口直接顯示選課信息

string studentsno;
        private void Student_Course_Load(object sender, EventArgs e)
        {
            Form1 m = new Form1();
            string select_name = m.Get();
            
            String conn = "Data Source =.; Initial Catalog = School;  Persist Security Info = True;User ID = sa; Password = 123";
            SqlConnection sqlconnection = new SqlConnection(conn);//實例化連接對象
            try
            {
                sqlconnection.Open();         
                String select_by_sno = "select UserSchoolID from SysUser where UserID='" + select_name + "'";
                SqlCommand cmd = new SqlCommand(select_by_sno, sqlconnection);
                SqlDataReader dr = cmd.ExecuteReader();//讀取數據
                dr.Read();
                if (dr.HasRows)
                    studentsno = dr[0].ToString();
                dr.Close();
                String select_sno = "select SC.Sno,Course.Cno,Cname,Ccredit from Course,SC where Course.Cno = SC.Cno and SC.Sno = '" + studentsno + "'";
                SqlCommand sqlcommand = new SqlCommand(select_sno, sqlconnection);
                SqlDataReader sqldatareader = sqlcommand.ExecuteReader();
                BindingSource bindingsource = new BindingSource();
                bindingsource.DataSource = sqldatareader;
                dataGridView1.DataSource = bindingsource;
            }
            catch
            {
                MessageBox.Show("查詢語句有誤,請認真檢查SQL語句");
            }
            finally
            {
                sqlconnection.Close();
            }

            // TODO: 這行代碼將數據加載到表“schoolDataSet6.Course”中。您可以根據需要移動或刪除它。
            this.courseTableAdapter.Fill(this.schoolDataSet6.Course);
        }

修改密碼
在這裏插入圖片描述
MD5加密

 public static string EncryptWithMD5(string source)      //MD5加密
        {
            byte[] sor = Encoding.UTF8.GetBytes(source);
            MD5 md5 = MD5.Create();
            byte[] result = md5.ComputeHash(sor);
            StringBuilder strbul = new StringBuilder(40);
            for (int i = 0; i < result.Length; i++)
            {
                strbul.Append(result[i].ToString("x2"));//加密結果"x2"結果爲32位,"x3"結果爲48位,"x4"結果爲64位
            }
            return strbul.ToString();
        }

輸入用戶名、新密碼、確認新密碼,輸入錯誤會提示

  private void buttonok_Click(object sender, EventArgs e)
        {
            try
            {
                Form1 m = new Form1();
                string select_name = m.Get();
                string newpassword = textBoxnewpassword.Text.Trim();
                string newpassword1 = textBoxnewpassword1.Text.Trim();
                string connString = "Data Source=.;Initial Catalog=School;Persist Security Info=True;User ID=sa;Password=123";//數據庫連接字符串
                SqlConnection connection = new SqlConnection(connString);//創建connection對象              
                connection.Open(); //打開數據庫連接

                if (textBoxusername.Text.Trim() == select_name)
                {
                    if (newpassword == newpassword1)//密碼與確認密碼的內容相同
                    {
                        string sql = "update SysUser set UserPassWord = @upw where UserID = @id";
                        SqlCommand cmd = new SqlCommand(sql, connection);

                        SqlParameter sqlParameter = new SqlParameter("@upw", EncryptWithMD5(textBoxnewpassword.Text.Trim()));
                        cmd.Parameters.Add(sqlParameter);
                        SqlParameter sqlParameter1 = new SqlParameter("@id", textBoxusername.Text.Trim());
                        cmd.Parameters.Add(sqlParameter1);

                        cmd.ExecuteNonQuery();
                        connection.Close();
                        MessageBox.Show("密碼修改成功!");
                    }
                    else
                    {
                        MessageBox.Show("請再次檢查輸入的密碼是否正確!");
                    }
                }
                else
                {
                    MessageBox.Show("請輸入正確的用戶名!");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }         
        }

密碼和輸入新密碼的格式限制

private void textBoxnewpassword_Leave(object sender, EventArgs e)//密碼
        {
            if (textBoxnewpassword.Text.Trim() != "")
            {
                //使用regex(正則表達式)進行格式設置 至少有數字、大寫字母、小寫字母各一個。最少3個字符、最長20個字符。
                Regex regex = new Regex(@"(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).{3,20}");
                if (regex.IsMatch(textBoxnewpassword.Text))//判斷格式是否符合要求
                {
                    //MessageBox.Show("輸入密碼格式正確!");
                }
                else
                {
                    MessageBox.Show("至少有數字、大寫字母、小寫字母各一個。最少3個字符、最長20個字符!");
                    textBoxnewpassword.Focus();
                }
            }
            else
            {
                MessageBox.Show("密碼不能爲空!");
            }
        }

        private void textBoxnewpassword1_Leave(object sender, EventArgs e)//確認新密碼
        {
            if (textBoxnewpassword1.Text.Trim() != "")
            {
                //使用regex(正則表達式)進行格式設置 至少有數字、大寫字母、小寫字母各一個。最少3個字符、最長20個字符。
                Regex regex = new Regex(@"(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).{3,20}");

                if (regex.IsMatch(textBoxnewpassword1.Text))//判斷格式是否符合要求
                {
                    //MessageBox.Show("輸入密碼格式正確!");
                }
                else
                {
                    MessageBox.Show("至少有數字、大寫字母、小寫字母各一個。最少3個字符、最長20個字符!");
                    textBoxnewpassword1.Focus();
                }
            }
            else
            {
                MessageBox.Show("確定密碼不能爲空!");
            }
        }
  • 管理員登錄
    選擇要進行的操作
    在這裏插入圖片描述
 private void buttonstudent_Click(object sender, EventArgs e)
        {
            this.Hide();
            Admin_Student ads = new Admin_Student();
            ads.ShowDialog();
            
        }

        private void buttonclose_Click(object sender, EventArgs e)
        {
            this.Close();
            Form1 f = new Form1();
            f.Show();
        }

        private void buttoncourse_Click(object sender, EventArgs e)
        {
            this.Hide();
            Admin_Course adc = new Admin_Course();
            adc.ShowDialog();
            
        }

        private void buttoninfo_Click(object sender, EventArgs e)//個人信息
        { 
            this.Hide();
            Admin_info adin = new Admin_info();
            adin.ShowDialog();
           
        }

        private void buttonlogin_Click(object sender, EventArgs e)//登錄日誌
        { 
            this.Hide();
            Admin_login adlogin = new Admin_login();
            adlogin.ShowDialog();
           
        }

        private void buttonsc_Click(object sender, EventArgs e)
        {
            this.Hide();
            Admin_SC adsc = new Admin_SC();
            adsc.ShowDialog();
            
        }

        private void buttonpassword_Click(object sender, EventArgs e)
        {
            this.Hide();
            Admin_password adpw = new Admin_password();
            adpw.ShowDialog();
            
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

學生表
在這裏插入圖片描述
增加:性別、年齡限制

        SqlConnection con = new SqlConnection("Data Source =.; Initial Catalog = School;  Persist Security Info = True;User ID = sa; Password = 123"); //連接數據庫
         private void buttonadd_Click(object sender, EventArgs e)    //增加
        {
            string StuSno = textBoxsno.Text.Trim();
            string StuSname = textBoxsname.Text.Trim();
            string StuSsex = textBoxssex.Text.Trim();
            string StuSage = textBoxsage.Text.Trim();
            string StuSdept = textBoxsdept.Text.Trim();
           
             try
             {
                if (StuSsex != "男" && StuSsex != "女")
                {
                    MessageBox.Show("性別必須輸入爲“男”或“女”");
                }
                
                con.Open();     //打開數據庫
                 string insertStr = "INSERT INTO Student(Sno,Sname,Ssex,Sage,Sdept)" + "VALUES('" + StuSno + "','" + StuSname + "','" + StuSsex + "'," + StuSage + ",'" + StuSdept + "')";
                 SqlCommand cmd = new SqlCommand(insertStr, con);
                 cmd.ExecuteNonQuery();      //將增加後的信息直接出來
             }
             catch
             {
                MessageBox.Show("輸入數據違反要求,請按照要求填寫信息!");
            }
             finally
             {
                con.Close();      //關閉數據庫
               //  con.Close();
             }
             this.studentTableAdapter.Fill(this.schoolDataSet.Student);          
        }

刪除:選擇整行刪除,已經選課的學生不可刪除

 private void buttondelete_Click(object sender, EventArgs e)     //刪除
        {
            try
            {
                con.Open();     //打開數據庫
                string select_Sno = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();//選擇的當前行第一列的值,也就是Sno
                string delete_by_Sno = "DELETE FROM Student WHERE Sno='" + select_Sno + "'";//sql刪除語句
                SqlCommand cmd = new SqlCommand(delete_by_Sno, con);
                cmd.ExecuteNonQuery();
            }
            catch
            {
                MessageBox.Show("該學生已選課,無法刪除!");
            }
            finally
            {
                // con.Dispose();      //關閉數據庫
                con.Close();
            }
            this.studentTableAdapter.Fill(this.schoolDataSet.Student);
        }

修改:根據學號修改姓名、性別、年齡、專業

private void buttonchange_Click(object sender, EventArgs e)     //修改,根據學號修改姓名、性別、年齡、專業
        {
            string StuSno = textBoxsno.Text.Trim();
            string StuSname = textBoxsname.Text.Trim();
            string StuSsex = textBoxssex.Text.Trim();
            string StuSage = textBoxsage.Text.Trim();
            string StuSdept = textBoxsdept.Text.Trim();
            try
            {
                con.Open();     //打開數據庫
                if (StuSno == "")//輸入的學號爲空
                {
                    MessageBox.Show("學號不能爲空!");
                }
                if (StuSname != "") //在Sname的文本框輸入內容,修改Sname
                {
                    string update_sname = "UPDATE Student SET Sname='" + StuSname + "'WHERE Sno='" + StuSno + "'";
                    SqlCommand cmd1 = new SqlCommand(update_sname, con);
                    cmd1.ExecuteNonQuery();
                }
                if (StuSsex != "")  //修改Ssex
                {
                    string update_sex = "UPDATE Student SET Ssex='" + StuSsex + "' WHERE Sno='" + StuSno + "'";
                    SqlCommand cmd2 = new SqlCommand(update_sex, con);
                    cmd2.ExecuteNonQuery();
                }
                if (StuSage != "")//修改Sage
                {                
                     string update_age = "UPDATE Student SET Sage='" + StuSage + " 'WHERE Sno='" + StuSno + "'";
                     SqlCommand cmd3 = new SqlCommand(update_age, con);
                    cmd3.ExecuteNonQuery();
                }
                if (StuSdept != "")//修改Sdept
                {
                    string update_sdept = "UPDATE Student SET Sdept='" + StuSdept + "' WHERE Sno='" + StuSno + "'";
                    SqlCommand cmd4 = new SqlCommand(update_sdept, con);
                    cmd4.ExecuteNonQuery();
                }               
            }
            catch
            {
                MessageBox.Show("輸入數據違反要求!");
            }
            finally
            {
                //con.Dispose();      //關閉數據庫
                con.Close();
            }
            this.studentTableAdapter.Fill(this.schoolDataSet.Student);
        }

查找

 private void buttonselect_Click(object sender, EventArgs e) //查找
        {
            string StuSno = textBoxsno.Text.Trim();
            string StuSname = textBoxsname.Text.Trim();
            string StuSsex = textBoxssex.Text.Trim();
            string StuSage = textBoxsage.Text.Trim();
            string StuSdept = textBoxsdept.Text.Trim();
            String conn = "Data Source =.; Initial Catalog = School;  Persist Security Info = True;User ID = sa; Password = 123";
            SqlConnection sqlconnection = new SqlConnection(conn);//實例化連接對象
            
            try
            {
                sqlconnection.Open();
                
                if (StuSno != "")//按照學號查找,只有一個
                {
                    String select_by_sno = "select * from Student where Sno='" + StuSno + "'";
                    SqlCommand sqlcommand = new SqlCommand(select_by_sno, sqlconnection);
                    SqlDataReader sqldatareader = sqlcommand.ExecuteReader();
                    BindingSource bindingsource = new BindingSource();
                    bindingsource.DataSource = sqldatareader;
                    dataGridView1.DataSource = bindingsource;
                    //將讀出來的值賦給數據源,再將數據源給dataGridView
                }
                if (StuSname != ""&&StuSsex==""&&StuSage==""&&StuSdept=="")//只按照姓名查找
                {
                    String select_by_sname = "select * from Student where Sname='" + StuSname + "'";
                   SqlCommand  sqlcommand = new SqlCommand(select_by_sname, sqlconnection);
                    SqlDataReader sqldatareader = sqlcommand.ExecuteReader();
                    BindingSource bindingsource = new BindingSource();
                    bindingsource.DataSource = sqldatareader;
                    dataGridView1.DataSource = bindingsource;
                    //將讀出來的值賦給數據源,再將數據源給dataGridView
                }
                if (StuSsex!=""&&StuSname==""&& StuSdept==""&&StuSage=="") //只按照性別查找
                {
                    String select_by_sex = "select * from Student where Ssex='" + StuSsex + "'";
                    SqlCommand sqlcommand = new SqlCommand(select_by_sex, sqlconnection);
                    SqlDataReader sqldatareader = sqlcommand.ExecuteReader();
                    BindingSource bindingsource = new BindingSource();
                    bindingsource.DataSource = sqldatareader;
                    dataGridView1.DataSource = bindingsource;
                    //將讀出來的值賦給數據源,再將數據源給dataGridView
                }
                if (StuSage != "" && StuSname == "" && StuSsex == "" && StuSdept == "")//只按照年齡查找
                {
                    String select_by_age = "select * from Student where Sage='" + StuSage + "'";
                    SqlCommand sqlcommand = new SqlCommand(select_by_age, sqlconnection);
                    SqlDataReader sqldatareader = sqlcommand.ExecuteReader();
                    BindingSource bindingsource = new BindingSource();
                    bindingsource.DataSource = sqldatareader;
                    dataGridView1.DataSource = bindingsource;
                    //將讀出來的值賦給數據源,再將數據源給dataGridView
                }
                if (StuSdept != "" && StuSname == "" && StuSsex == "" && StuSage == "")//只按照系別查找
                {
                    String select_by_sdept = "select * from Student where Sdept='" + StuSdept + "'";
                    SqlCommand sqlcommand = new SqlCommand(select_by_sdept, sqlconnection);
                    SqlDataReader sqldatareader = sqlcommand.ExecuteReader();
                    BindingSource bindingsource = new BindingSource();
                    bindingsource.DataSource = sqldatareader;
                    dataGridView1.DataSource = bindingsource;
                    //將讀出來的值賦給數據源,再將數據源給dataGridView
                }
                 if(StuSsex!=""&&StuSage!=""&&StuSdept=="")//按照性別和年齡查找
                {
                    String select_by_sexage = "select * from Student where Ssex='" + StuSsex + "' and Sage='"+StuSage+"'";
                    SqlCommand sqlcommand = new SqlCommand(select_by_sexage, sqlconnection);
                    SqlDataReader sqldatareader = sqlcommand.ExecuteReader();
                    BindingSource bindingsource = new BindingSource();
                    bindingsource.DataSource = sqldatareader;
                    dataGridView1.DataSource = bindingsource;
                }
                if (StuSsex != "" && StuSdept != "" && StuSage == "")//按照性別和系別查找
                {
                    String select_by_sexdept = "select * from Student where Ssex='" + StuSsex + "' and Sdept='" + StuSdept + "'";
                    SqlCommand sqlcommand = new SqlCommand(select_by_sexdept, sqlconnection);
                    SqlDataReader sqldatareader = sqlcommand.ExecuteReader();
                    BindingSource bindingsource = new BindingSource();
                    bindingsource.DataSource = sqldatareader;
                    dataGridView1.DataSource = bindingsource;
                }
                if (StuSage != "" && StuSdept != "" && StuSsex == "")//按照年齡和系別查找
                {
                    String select_by_agedept = "select * from Student where Sage='" + StuSage + "' and Sdept='" + StuSdept + "'";
                    SqlCommand sqlcommand = new SqlCommand(select_by_agedept, sqlconnection);
                    SqlDataReader sqldatareader = sqlcommand.ExecuteReader();
                    BindingSource bindingsource = new BindingSource();
                    bindingsource.DataSource = sqldatareader;
                    dataGridView1.DataSource = bindingsource;
                }
                if (StuSage != "" && StuSdept != "" && StuSsex != "")//按照年齡、系別、性別查找
                {
                    String select_by_agedeptsex = "select * from Student where Sage='" + StuSage + "' and Sdept='" + StuSdept + "' and Ssex='"+StuSsex+"'";
                    SqlCommand sqlcommand = new SqlCommand(select_by_agedeptsex, sqlconnection);
                    SqlDataReader sqldatareader = sqlcommand.ExecuteReader();
                    BindingSource bindingsource = new BindingSource();
                    bindingsource.DataSource = sqldatareader;
                    dataGridView1.DataSource = bindingsource;
                }
            }
            catch
            {
                MessageBox.Show("查詢語句有誤,請認真檢查SQL語句");
            }
            finally
            {
                sqlconnection.Close();              
            }
        }

清除文本框內容

  public void clear()//將文本框的內容全部清除
        {
            textBoxsno.Text = "";
            textBoxsname.Text = "";
            textBoxssex.Text = "";
            textBoxsage.Text = "";
            textBoxsdept.Text = "";
        }

課程表
在這裏插入圖片描述
增加:

SqlConnection con = new SqlConnection("Data Source =.; Initial Catalog = School;  Persist Security Info = True;User ID = sa; Password = 123"); //連接數據庫

       
        private void buttonadd_Click(object sender, EventArgs e)//增加
        {
            string CouCno = textBoxcno.Text.Trim();
            string CouCname = textBoxcname.Text.Trim();
            string CouCpno =textBoxcpno.Text.Trim();
            string CouCcredit = textBoxcredit.Text.Trim();
            try
            {
                con.Open();     //打開數據庫
                string insertCou = "INSERT INTO Course(Cno,Cname,Cpno,Ccredit)" + "VALUES('" + CouCno + "','" + CouCname + "','" + CouCpno + "'," + CouCcredit+ ")";
                SqlCommand cmd = new SqlCommand(insertCou, con);
                cmd.ExecuteNonQuery();      //將增加後的信息直接出來
            }
            catch
            {
                MessageBox.Show("輸入數據違反要求!");
            }
            finally 
            {
                con.Close();
            }
            this.courseTableAdapter.Fill(this.schoolDataSet1.Course);
        }

刪除:已經被學生選課的課程無法刪除

 private void buttondelete_Click(object sender, EventArgs e)//刪除
        {
            try
            {
                con.Open();     //打開數據庫
                string select_Cno = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();//選擇的當前行第一列的值,也就是Cno
                string delete_by_Cno = "DELETE FROM Course WHERE Cno='" + select_Cno + "'";//sql刪除語句
                SqlCommand cmd = new SqlCommand(delete_by_Cno, con);
                cmd.ExecuteNonQuery();
            }
            catch
            {
                MessageBox.Show("已有學生選課或作爲先行課,無法刪除!");
            }
            finally
            {
                // con.Dispose();      //關閉數據庫
                con.Close();
            }
            this.courseTableAdapter.Fill(this.schoolDataSet1.Course);
        }

修改:根據課程號修改或者根據課程名修改

 private void buttonchange_Click(object sender, EventArgs e)//修改
        {
            string CouCno = textBoxcno.Text.Trim();
            string CouCname = textBoxcname.Text.Trim();
            string CouCpno = textBoxcpno.Text.Trim();
            string CouCcredit = textBoxcredit.Text.Trim();
            try
            {
                con.Open();     //打開數據庫
                
                if (CouCname != "") //修改課程名稱,只能根據課程號修改
                {
                    
                    string update_cname = "UPDATE Course SET Cname='" + CouCname + "'WHERE Cno='" + CouCno + "'";
                    SqlCommand cmd = new SqlCommand(update_cname, con);
                    cmd.ExecuteNonQuery();
                }
                 if ( CouCpno != "" &&CouCno != "" || CouCname != ""&& CouCpno != "")  //修改Cpno,通過課程號修改一門課的或者通過課程名修改多門課的
                 {
                     string update_cpno = "UPDATE Course SET Cpno='" + CouCpno + "' WHERE Cno='" + CouCno + "' OR Cname='"+CouCname+"'";
                     SqlCommand cmd2 = new SqlCommand(update_cpno, con);
                     cmd2.ExecuteNonQuery();
                 }

                 if (CouCcredit != "" && CouCno != "" || CouCname != "" && CouCcredit != "")//修改Credit,通過課程號修改一門課的或者通過課程名修改多門課的
                 {
                     string update_credit = "UPDATE Course SET Ccredit='" + CouCcredit + " 'WHERE Cno='" + CouCno + "' OR Cname='"+CouCname+"'";
                     SqlCommand cmd3 = new SqlCommand(update_credit, con);
                     cmd3.ExecuteNonQuery();
                 }
              
            }
            catch
            {
                MessageBox.Show("輸入數據違反要求!");
            }
            finally
            {
                //con.Dispose();      //關閉數據庫
                con.Close();
            }
            this.courseTableAdapter.Fill(this.schoolDataSet1.Course);
        }

查找

private void buttonselect_Click(object sender, EventArgs e)//查找
        {
            string CouCno = textBoxcno.Text.Trim();
            string CouCname = textBoxcname.Text.Trim();
            string CouCpno = textBoxcpno.Text.Trim();
            string CouCcredit = textBoxcredit.Text.Trim();
            String conn = "Data Source =.; Initial Catalog = School;  Persist Security Info = True;User ID = sa; Password = 123";
            SqlConnection sqlconnection = new SqlConnection(conn);//實例化連接對象

            try
            {
                sqlconnection.Open();

                if (CouCno != "")//按照課序號查找,只有一個
                {
                    String select_by_cno = "select * from Course where Cno='" + CouCno + "'";
                    SqlCommand sqlcommand = new SqlCommand(select_by_cno, sqlconnection);
                    SqlDataReader sqldatareader = sqlcommand.ExecuteReader();
                    BindingSource bindingsource = new BindingSource();
                    bindingsource.DataSource = sqldatareader;
                    dataGridView1.DataSource = bindingsource;
                    //將讀出來的值賦給數據源,再將數據源給dataGridView
                }
                if (CouCname != "" && CouCpno == "" && CouCcredit == "")//按照課程名查找
                {
                    String select_by_cname = "select * from Course where Cname='" + CouCname + "'";
                    SqlCommand sqlcommand = new SqlCommand(select_by_cname, sqlconnection);
                    SqlDataReader sqldatareader = sqlcommand.ExecuteReader();
                    BindingSource bindingsource = new BindingSource();
                    bindingsource.DataSource = sqldatareader;
                    dataGridView1.DataSource = bindingsource;
                }
                if (CouCpno != "" && CouCname == "" && CouCcredit == "")//按照Cpno查找
                {
                    String select_by_cpno = "select * from Course where Cpno='" + CouCpno + "'";
                    SqlCommand sqlcommand = new SqlCommand(select_by_cpno, sqlconnection);
                    SqlDataReader sqldatareader = sqlcommand.ExecuteReader();
                    BindingSource bindingsource = new BindingSource();
                    bindingsource.DataSource = sqldatareader;
                    dataGridView1.DataSource = bindingsource;
                }
                if (CouCcredit != "" && CouCname == "" && CouCpno == "")//按照Credit查找
                {
                    String select_by_credit = "select * from Course where Ccredit='" + CouCcredit + "'";
                    SqlCommand sqlcommand = new SqlCommand(select_by_credit, sqlconnection);
                    SqlDataReader sqldatareader = sqlcommand.ExecuteReader();
                    BindingSource bindingsource = new BindingSource();
                    bindingsource.DataSource = sqldatareader;
                    dataGridView1.DataSource = bindingsource;
                }
                if (CouCname != "" && CouCpno != "" && CouCcredit == "")//按照Cname和Cpno查找
                {
                    String select_by_namepno = "select * from Course where Cname='" + CouCname + "' AND Cpno='"+CouCpno+"'";
                    SqlCommand sqlcommand = new SqlCommand(select_by_namepno, sqlconnection);
                    SqlDataReader sqldatareader = sqlcommand.ExecuteReader();
                    BindingSource bindingsource = new BindingSource();
                    bindingsource.DataSource = sqldatareader;
                    dataGridView1.DataSource = bindingsource;
                }
                if (CouCname != "" && CouCcredit != "" && CouCpno == "")//按照Cname和Ccredit查找
                {
                    String select_by_namecredit = "select * from Course where Cname='" + CouCname + "' AND Ccredit='" + CouCcredit + "'";
                    SqlCommand sqlcommand = new SqlCommand(select_by_namecredit, sqlconnection);
                    SqlDataReader sqldatareader = sqlcommand.ExecuteReader();
                    BindingSource bindingsource = new BindingSource();
                    bindingsource.DataSource = sqldatareader;
                    dataGridView1.DataSource = bindingsource;
                }
                if (CouCpno != "" && CouCcredit != "" && CouCname == "")//按照Cpno和Ccredit查找
                {
                    String select_by_pnocredit = "select * from Course where Cpno='" + CouCpno + "' AND Ccredit='" + CouCcredit + "'";
                    SqlCommand sqlcommand = new SqlCommand(select_by_pnocredit, sqlconnection);
                    SqlDataReader sqldatareader = sqlcommand.ExecuteReader();
                    BindingSource bindingsource = new BindingSource();
                    bindingsource.DataSource = sqldatareader;
                    dataGridView1.DataSource = bindingsource;
                }
                if (CouCname != "" && CouCpno != "" && CouCcredit != "")//按照Cname和Cpno和Ccredit查找
                {
                    String select_by_pnocreditname = "select * from Course where Cpno='" + CouCpno + "' AND Ccredit='" + CouCcredit + "' AND Cname='"+CouCname+"'";
                    SqlCommand sqlcommand = new SqlCommand(select_by_pnocreditname, sqlconnection);
                    SqlDataReader sqldatareader = sqlcommand.ExecuteReader();
                    BindingSource bindingsource = new BindingSource();
                    bindingsource.DataSource = sqldatareader;
                    dataGridView1.DataSource = bindingsource;
                }
            }
            catch
            {
                MessageBox.Show("查詢語句有誤,請認真檢查SQL語句");
            }
            finally
            {
                sqlconnection.Close();
            }
        }

學生-課程表
在這裏插入圖片描述
增加

  private void buttonadd_Click(object sender, EventArgs e)//增加
        {
            string SCsno = textBoxsno.Text.Trim();
            string SCcno = textBoxcno.Text.Trim();
            string SCgrade = textBoxgrade.Text.Trim();
            try
            {
                con.Open();     //打開數據庫
                string insertsc = "INSERT INTO SC(Sno,Cno,Grade)" + "VALUES('" + SCsno + "','" + SCcno + "'," +SCgrade +")";
                SqlCommand cmd = new SqlCommand(insertsc, con);
                cmd.ExecuteNonQuery();      //將增加後的信息直接出來
            }
            catch
            {
                MessageBox.Show("輸入數據違反要求!");
            }
            finally
            {
                con.Close();      //關閉數據庫                                
            }
            this.sCTableAdapter.Fill(this.schoolDataSet3.SC);
        }

刪除

 private void buttondelete_Click(object sender, EventArgs e)//刪除
        {
            try
            {         
               con.Open(); //打開數據庫
                string select_Sno = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();//選擇的當前行第一列的值,也就是Sno
                string select_Cno = dataGridView1.SelectedRows[0].Cells[1].Value.ToString();//選擇當前行第2列的值,也就是Cno
                string delete_by_SnoCno = "delete from SC where Sno='" + select_Sno + "' and Cno='" + select_Cno + "'";//sql刪除語句
                SqlCommand cmd = new SqlCommand(delete_by_SnoCno, con);
                cmd.ExecuteNonQuery();             
            }
            catch
            {
                MessageBox.Show("請選擇正確行!");
            }
            finally
            {                 
                con.Close(); //關閉數據庫
            }
            this.sCTableAdapter.Fill(this.schoolDataSet3.SC);
        }

修改:修改成績

 private void buttonchange_Click(object sender, EventArgs e)//修改
        {
            string SCsno = textBoxsno.Text.Trim();
            string SCcno = textBoxcno.Text.Trim();
            string SCgrade = textBoxgrade.Text.Trim();

            try
            {
                con.Open();     //打開數據庫

                if (SCsno == "" || SCcno == "")
                {
                    MessageBox.Show("Sno和Cno不能爲空!");
                }
                if (SCgrade != "")//根據Sno和Cno修改Grade
                {
                    string update_grade = "UPDATE SC SET Grade='" + SCgrade + "' WHERE Sno='"+SCsno+"' AND Cno='"+SCcno+"'";
                    SqlCommand cmd = new SqlCommand(update_grade,con);
                    cmd.ExecuteNonQuery();
                }               
            }
            catch
            {
                MessageBox.Show("輸入數據違反要求!");
            }
            finally
            {
                   //關閉數據庫
                con.Close();
            }
            this.sCTableAdapter.Fill(this.schoolDataSet3.SC);
        }

查找

 private void buttonselect_Click(object sender, EventArgs e)//查找
        {
            this.Hide();
            Admin_SC_grade adsc = new Admin_SC_grade();
            adsc.ShowDialog();        
        }

查找
在這裏插入圖片描述
查找,Sno、Cno、Grade查找

 private void buttonselect_Click(object sender, EventArgs e)
        {
            string SCsno = textBoxsno.Text.Trim();
            string SCcno = textBoxcno.Text.Trim();
            string SCgrade = textBoxgrade.Text.Trim();          
            SqlConnection sqlconnection = new SqlConnection(conn);//實例化連接對象
            try
            {
                sqlconnection.Open();

                if (SCcno != "" && SCsno != "")//按照Sno和Cno查詢
                {
                    String select_by_snocno = "select * from SC where Sno='" + SCsno + "' AND Cno='" + SCcno + "'";
                    SqlCommand sqlcommand = new SqlCommand(select_by_snocno, sqlconnection);
                    SqlDataReader sqldatareader = sqlcommand.ExecuteReader();
                    BindingSource bindingsource = new BindingSource();
                    bindingsource.DataSource = sqldatareader;
                    dataGridView1.DataSource = bindingsource;
                    //將讀出來的值賦給數據源,再將數據源給dataGridView
                }
                if (SCsno != "" && SCcno == "" && SCgrade == "")//按照學號查詢
                {
                    String select_by_sno = "select * from SC where Sno='" + SCsno + "'";
                    SqlCommand sqlcommand = new SqlCommand(select_by_sno, sqlconnection);
                    SqlDataReader sqldatareader = sqlcommand.ExecuteReader();
                    BindingSource bindingsource = new BindingSource();
                    bindingsource.DataSource = sqldatareader;
                    dataGridView1.DataSource = bindingsource;
                }
                if (SCcno != "" && SCsno == "" && SCgrade == "")//按照Cno查找
                {
                    String select_by_cno = "select * from SC where Cno='" + SCcno + "'";
                    SqlCommand sqlcommand = new SqlCommand(select_by_cno, sqlconnection);
                    SqlDataReader sqldatareader = sqlcommand.ExecuteReader();
                    BindingSource bindingsource = new BindingSource();
                    bindingsource.DataSource = sqldatareader;
                    dataGridView1.DataSource = bindingsource;
                }
                if (SCgrade != "" && SCsno == "" && SCcno == "")//按照Grade查詢
                {
                    String select_by_grade = "select * from SC where Grade='" + SCgrade + "'";
                    SqlCommand sqlcommand = new SqlCommand(select_by_grade, sqlconnection);
                    SqlDataReader sqldatareader = sqlcommand.ExecuteReader();
                    BindingSource bindingsource = new BindingSource();
                    bindingsource.DataSource = sqldatareader;
                    dataGridView1.DataSource = bindingsource;
                }
               
                if (SCcno != "" && SCgrade != "" && SCsno == "")//按照Cno和Grade查詢
                {
                    String select_by_cnograde = "select * from SC where Cno='" + SCcno + "' and Grade='" + SCgrade + "'";
                    SqlCommand sqlcommand = new SqlCommand(select_by_cnograde, sqlconnection);
                    SqlDataReader sqldatareader = sqlcommand.ExecuteReader();
                    BindingSource bindingsource = new BindingSource();
                    bindingsource.DataSource = sqldatareader;
                    dataGridView1.DataSource = bindingsource;
                }
                if (SCsno != "" && SCgrade != "" && SCcno == "")//按照Sno和Grade查詢
                {
                    String select_by_snograde = "select * from SC where Sno='" + SCsno + "' and Grade='" + SCgrade + "'";
                    SqlCommand sqlcommand = new SqlCommand(select_by_snograde, sqlconnection);
                    SqlDataReader sqldatareader = sqlcommand.ExecuteReader();
                    BindingSource bindingsource = new BindingSource();
                    bindingsource.DataSource = sqldatareader;
                    dataGridView1.DataSource = bindingsource;
                }
            }
            catch
            {
                MessageBox.Show("查詢語句有誤,請認真檢查SQL語句");
            }
            finally
            {
                sqlconnection.Close();
            }
        }

查找不及格成績

 private void buttonnograde_Click(object sender, EventArgs e)//不及格成績
        {
            string SCsno = textBoxsno.Text.Trim();
            string SCcno = textBoxcno.Text.Trim();          
            SqlConnection sqlconnection = new SqlConnection(conn);//實例化連接對象

            try
            {
                sqlconnection.Open();

                if (SCsno != "" && SCcno == "")//查詢某個學生的不及格成績
                {
                    string select_nograde = "select * from SC where Grade<60 and Sno='" + SCsno + "'";
                       
                    SqlCommand sqlcommand = new SqlCommand(select_nograde, sqlconnection);
                    SqlDataReader sqldatareader = sqlcommand.ExecuteReader();
                    BindingSource bindingsource = new BindingSource();
                    bindingsource.DataSource = sqldatareader;
                    dataGridView1.DataSource = bindingsource;
                }
                if (SCcno != "" && SCsno == "")//查詢某個課程的不及格成績
                {
                    string select_nograde = "select * from SC where Grade<60 and Cno='" + SCcno + "'";
                    SqlCommand sqlcommand = new SqlCommand(select_nograde, sqlconnection);
                    SqlDataReader sqldatareader = sqlcommand.ExecuteReader();
                    BindingSource bindingsource = new BindingSource();
                    bindingsource.DataSource = sqldatareader;
                    dataGridView1.DataSource = bindingsource;
                }
            }
            catch
            {
                MessageBox.Show("查詢語句有誤,請認真檢查SQL語句");
            }
            finally
            {
                sqlconnection.Close();
            }
        }

按分數段查詢

 private void button3_Click(object sender, EventArgs e)//分數段查詢
        {
            string SCcno = textBoxcno.Text.Trim();
            string SCmin = textBoxmin.Text.Trim();
            string SCmax = textBoxmax.Text.Trim();
            String conn = "Data Source =.; Initial Catalog = School;  Persist Security Info = True;User ID = sa; Password = 123";
            SqlConnection sqlconnection = new SqlConnection(conn);//實例化連接對象           
            try
            {
                sqlconnection.Open();
                if (SCmin != "" && SCmax != "" && SCcno != "")//查詢在特定分數段的學生
                {
                    String select_by_minmax = "select * from SC where Cno='" + SCcno + "' and Grade between '" + SCmin + "' and '" + SCmax + "'";
                    SqlCommand sqlcommand = new SqlCommand(select_by_minmax, sqlconnection);
                    SqlDataReader sqldatareader = sqlcommand.ExecuteReader();
                    BindingSource bindingsource = new BindingSource();
                    bindingsource.DataSource = sqldatareader;
                    dataGridView1.DataSource = bindingsource;                   
                } 
                if (SCcno != "" && SCmin != "" && SCmax == "")//查詢在特定成績之上的學生     
                {
                    String select_by_cnograde = "select * from SC where Cno='" + SCcno + "' and Grade>'" + SCmin + "'";
                    SqlCommand sqlcommand = new SqlCommand(select_by_cnograde, sqlconnection);
                    SqlDataReader sqldatareader = sqlcommand.ExecuteReader();
                    BindingSource bindingsource = new BindingSource();
                    bindingsource.DataSource = sqldatareader;
                    dataGridView1.DataSource = bindingsource;
                }
                 if (SCcno != "" && SCmin == "" && SCmax != "")//查詢在特定成績之下的學生
                {
                    String select_by_cnograde = "select * from SC where Cno='" + SCcno + "' and Grade<'" + SCmax + "'";
                    SqlCommand sqlcommand = new SqlCommand(select_by_cnograde, sqlconnection);
                    SqlDataReader sqldatareader = sqlcommand.ExecuteReader();
                    BindingSource bindingsource = new BindingSource();
                    bindingsource.DataSource = sqldatareader;
                    dataGridView1.DataSource = bindingsource;
                }
            }
            catch
            {
                MessageBox.Show("查詢語句有誤,請認真檢查SQL語句");
            }
            finally
            {
                sqlconnection.Close();

            }
        }

登錄日誌
在這裏插入圖片描述
刷新按鈕

 private void buttonchange_Click(object sender, EventArgs e)//刷新
        {
            this.sysLogTableAdapter.Fill(this.schoolDataSet2.SysLog);
        }

個人信息
在這裏插入圖片描述
顯示個人信息

 private void Admin_info_Load(object sender, EventArgs e)
        {
            try
            {
                Form1 m = new Form1();
                string select_name = m.Get();
                string connString = "Data Source=.;Initial Catalog=School;Persist Security Info=True;User ID=sa;Password=123";//數據庫連接字符串
                SqlConnection connection = new SqlConnection(connString);//創建connection對象              
                connection.Open(); //打開數據庫連接

                //顯示信息
                //在顯示出生日期,注意DataTime格式的轉換,以及完成查詢後的標籤內容的轉換                
                string select_a = "select Ano,Aname,Asex,UserMobile,UserBirthday,Asalary,Atitle from Admin,SysUser where Admin.Ano=SysUser.UserSchoolID and UserID='" + select_name + "'";
                SqlCommand cmd = new SqlCommand(select_a, connection);
                SqlDataReader dr = cmd.ExecuteReader();//讀取數據
                dr.Read();
                if (dr.HasRows)
                {
                    labelno.Text = dr[0].ToString();
                    labelname.Text = dr[1].ToString();
                    labelsex.Text = dr[2].ToString();
                    labelphone.Text = dr[3].ToString();                 
                     labelbirth.Text = Convert.ToString(dr.GetDateTime(4).ToShortDateString());
                    //出生日期只顯示年月日
                    labelsalary.Text = dr[5].ToString();
                    labeltitle.Text = dr[6].ToString();
                }
                else { MessageBox.Show("您的信息還未錄入!"); }
                dr.Close();

                //顯示圖片
                string sql = "select UserPhoto from SysUser where UserID = '" + select_name + "'";                
                SqlCommand command = new SqlCommand(sql, connection);//創建SqlCommand對象
                //創建DataAdapter對象
                SqlDataAdapter dataAdapter = new SqlDataAdapter(command);
                //創建DataSet對象
                DataSet dataSet = new DataSet();
                dataAdapter.Fill(dataSet, "SysUser");
                int c = dataSet.Tables["SysUser"].Rows.Count;
                if (c > 0)
                {
                    Byte[] mybyte = new byte[0];
                    mybyte = (Byte[])(dataSet.Tables["SysUser"].Rows[c - 1]["UserPhoto"]);
                    MemoryStream ms = new MemoryStream(mybyte);
                    pictureBox1.Image = Image.FromStream(ms);
                }
                else
                    pictureBox1.Image = null;
                connection.Close();
                }
           
            catch
            {
                MessageBox.Show("顯示信息失敗!");
            }
            
        }

修改密碼
在這裏插入圖片描述
MD5加密

  public static string EncryptWithMD5(string source)      //MD5加密
        {
            byte[] sor = Encoding.UTF8.GetBytes(source);
            MD5 md5 = MD5.Create();
            byte[] result = md5.ComputeHash(sor);
            StringBuilder strbul = new StringBuilder(40);
            for (int i = 0; i < result.Length; i++)
            {
                strbul.Append(result[i].ToString("x2"));//加密結果"x2"結果爲32位,"x3"結果爲48位,"x4"結果爲64位
            }
            return strbul.ToString();
        }

點擊確定按鈕,密碼修改成功

  private void buttonok_Click(object sender, EventArgs e)
        {
            try
            {
                Form1 m = new Form1();
                string select_name = m.Get();
                string newpassword = textBoxnewpassword.Text.Trim();
                string newpassword1 = textBoxnewpassword1.Text.Trim();

                string connString = "Data Source=.;Initial Catalog=School;Persist Security Info=True;User ID=sa;Password=123";//數據庫連接字符串
                SqlConnection connection = new SqlConnection(connString);//創建connection對象              
                connection.Open(); //打開數據庫連接

                if (textBoxusername.Text.Trim() == select_name)
                {
                    if (newpassword == newpassword1)//密碼與確認密碼的內容相同
                    {
                        string sql = "update SysUser set UserPassWord = @upw where UserID = @id";
                        SqlCommand cmd = new SqlCommand(sql, connection);

                        SqlParameter sqlParameter = new SqlParameter("@upw", EncryptWithMD5(textBoxnewpassword.Text.Trim()));
                        cmd.Parameters.Add(sqlParameter);
                        SqlParameter sqlParameter1 = new SqlParameter("@id", textBoxusername.Text.Trim());
                        cmd.Parameters.Add(sqlParameter1);

                        cmd.ExecuteNonQuery();
                        connection.Close();
                        MessageBox.Show("密碼修改成功!");
                    }
                    else
                    {
                        MessageBox.Show("請再次檢查輸入的密碼是否正確!");
                    }
                }
                else
                {
                    MessageBox.Show("請輸入正確的用戶名!");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
           // this.Close();
        }

新密碼和確認新密碼的格式限制

 private void textBoxnewpassword_Leave(object sender, EventArgs e)
        {
            if (textBoxnewpassword.Text.Trim() != "")
            {
                //使用regex(正則表達式)進行格式設置 至少有數字、大寫字母、小寫字母各一個。最少3個字符、最長20個字符。
                Regex regex = new Regex(@"(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).{3,20}");

                if (regex.IsMatch(textBoxnewpassword.Text))//判斷格式是否符合要求
                {
                    //MessageBox.Show("輸入密碼格式正確!");
                }
                else
                {
                    MessageBox.Show("至少有數字、大寫字母、小寫字母各一個。最少3個字符、最長20個字符!");
                    textBoxnewpassword.Focus();
                }
            }
            else
            {
                MessageBox.Show("密碼不能爲空!");
            }
        }

        private void textBoxnewpassword1_Leave(object sender, EventArgs e)
        {
            if (textBoxnewpassword1.Text.Trim() != "")
            {
                //使用regex(正則表達式)進行格式設置 至少有數字、大寫字母、小寫字母各一個。最少3個字符、最長20個字符。
                Regex regex = new Regex(@"(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).{3,20}");

                if (regex.IsMatch(textBoxnewpassword1.Text))//判斷格式是否符合要求
                {
                    //MessageBox.Show("輸入密碼格式正確!");
                }
                else
                {
                    MessageBox.Show("至少有數字、大寫字母、小寫字母各一個。最少3個字符、最長20個字符!");
                    textBoxnewpassword1.Focus();
                }
            }
            else
            {
                MessageBox.Show("確定密碼不能爲空!");
            }
        }

視頻講解鏈接:視頻講解
代碼下載:代碼

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章