這篇文章主要介紹了C#中如何實現登錄功能,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
新建一個數據庫StudentDB
-- 使用master 數據庫 use master go if exists(select *from sysdatabases where name='StudentDB') drop database StudentDB go create database StudentDB go
在StudentDB中新建三張表
use StudentDB
go
-- 新建學生表
if exists (select *from sysobjects where name='Student')
drop table Student
go
create table Student
(
stuId int primary key identity(2000,1),
stuName varchar(30) not null,
stuSex char(2) not null,
stuAge int not null,
stuTel varchar(11) not null,
stuPWd varchar(30) not null
)
-- 添加學生表的數據
insert into Student (stuName,stuSex,stuAge,stuTel,stuPWd)values('張三','男',21,'12345678543','123456')
insert into Student (stuName,stuSex,stuAge,stuTel,stuPWd)values('趙六','男',21,'12345678543','123456')
insert into Student (stuName,stuSex,stuAge,stuTel,stuPWd)values('韓菲','女',20,'12345678543','123456')
-- 新建教師表
if exists (select *from sysobjects where name='Teacher')
drop table Teacher
go
create table Teacher
(
tId int primary key identity(4000,1),
tName varchar(30) not null,
tSex char(2) not null,
tAge int not null,
tTel varchar(11) not null,
tTitle varchar(20),
tPwd varchar(30) not null
)
--添加教師表
insert into Teacher(tName,tSex,tAge,tTel,tTitle,tPwd)values('xx','男',32,'12345678901','副教授','123456')
-- 新建管理員
if exists (select *from sysobjects where name='Admin')
drop table Admin
go
create table Admin
(
adminId int primary key identity(4000,1),
adminName varchar(30) not null,
adminPWd varchar(30) not null
)
-- 添加管理員表
insert into Admin(adminName,adminPwd) values('admin','123456')新建一個winform 項目,修改文本框name 為,txtUserName,txtPwd;登錄按鈕name 為btnLogin、btnExit。

功能實現分析
當用戶點擊登錄的時候,程序首先判斷用戶名、密碼是否為空,然后再根據單選按鈕的值,去判斷是哪一個角色進行登錄。
上面的事情做好以后,我們要去把用戶名和密碼拿到數據庫進行比較。先使用用戶名當作查詢條件,返回一個用戶對象(管理員、學生、教師,根據具體情況而定,因為我們是用主鍵當作用戶名,主鍵可以區分一個用戶,所以使用用戶名查詢只返回一條數據)。判斷對象是否為null,如果為null則說明用戶不存在。否則就判斷密碼是否正確。
準備實體類
在項目中新建三個類,類名和表名一致,字段名和表里面的字段名一致。
添加類,選中項目->添加->類
管理員類
public class Admin
{
public int adminId { get; set; }
public String adminName { get; set; }
public String adminPwd { get; set; }
}學生類
public class Student
{
public int stuId { get; set; }
public string stuName { get; set; }
public string stuSex { get; set; }
public int stuAge { get; set; }
public string stuTel { get; set; }
public string stuPwd { get; set; }
}教師類
public class Teacher
{
public int tId { get; set; }
public string tName { get; set; }
public string tSex { get; set; }
public int tAge { get; set; }
public string tTel { get; set; }
public string tTitle { get; set; }
public string tPWd { get; set; }
}準備DBHelper類
public class DbHelper
{
/// <summary>
/// 獲取連接對象
/// </summary>
/// <returns></returns>
public static SqlConnection GetConnection()
{
SqlConnection conn = null;
try
{
//可能發生錯誤的代碼
if (conn == null)
{
conn = new SqlConnection();
conn.ConnectionString = ConfigurationManager.ConnectionStrings["connString"].ToString();
conn.Open();
conn.Close();
}
return conn;
}
catch (Exception ex)
{
//發生異常以后要做的事情
throw ex; // 把問題拋出,讓程序員知道那里出了錯誤
}
}
/// <summary>
/// 執行增刪改
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public static int GetExcuet(string sql)
{
// 1. 獲取連接對象
SqlConnection conn = GetConnection();
try
{
// 2.打開鏈接
conn.Open();
//3.創建SqlCommand對象,sql語句,連接對象
SqlCommand cmd = new SqlCommand(sql, conn);
// 4.執行SQL,并返回受影響的行數
return cmd.ExecuteNonQuery(); ;
}
catch (Exception ex)
{
throw ex;
}
finally
{
conn.Close();
conn.Dispose();
}
}
/// <summary>
/// 返回執行查詢的結果
/// </summary>
/// <returns></returns>
public static DataTable GetDataSet(String sql)
{
try
{
// 1.獲取鏈接對象
SqlConnection conn = GetConnection();
//2.創建適配器對象
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
//3.創建DataSet 對象
DataSet ds = new DataSet();
da.Fill(ds);
return ds.Tables[0];
}
catch (Exception ex)
{
throw ex;
}
}
}在App.config中添加 數據庫連接字符串,在configuration標簽下進行添加
<connectionStrings> <add name="connString" connectionString="Data Source=.;Initial Catalog=StudentDB;Persist Security Info=True;User ID=sa;Password=123456"/> </connectionStrings>
實現點擊事件
當用戶點擊時候我們就去執行登錄事件
根據我們分析,我們首先要判斷用戶和密碼是否正確
//獲取用戶名和密碼
string username = txtUserName.Text.Trim();
string pwd = txtPwd.Text.Trim();
//當用戶名為空的時候就不往下面執行了
if (username.Equals(""))
{
MessageBox.Show("用戶名不能為空");
return;
}
if (pwd.Equals(""))
{
MessageBox.Show("密碼不能為空");
return;
}在判斷完所有的公共問題以后,接下來我們就要去判斷是哪一個用戶進行的登錄的,我們可以通過單選按鈕的checked屬性,進行判斷,然后分別去調用他們進行登錄的方法。
//管理員登錄
if (radAdmin.Checked)
{
AdminLogin(username);
}
//學生登錄
if (radStudent.Checked)
{
StudentLogin();
}
//教師登錄
if (radTeacher.Checked)
{
TeacherLogin();
}管理員登錄方法實現,根據管理員的用戶名進行查詢,判斷返回表的行數,如果行數小于1,那么表示改用戶不存在,返回null,否則返回一個管理員對象。其他的類似
private Admin AdminLogin(String username)
{
string sql = string.Format("select *from Admin where adminId={0}",username);
DataTable table= DbHelper.GetDataSet(sql);
//判斷表的行數,大于等于1表示有數據,用戶存在,否則返回null
if (table.Rows.Count < 1) return null;
//新建一個admin對象
Admin admin = new Admin();
admin.adminId = Convert.ToInt32(table.Rows[0]["adminId"]);
admin.adminName = table.Rows[0]["adminName"].ToString();
admin.adminPwd = table.Rows[0]["adminPwd"].ToString();
return admin;
}學生的登錄方法
private Student StudentLogin(string username)
{
string sql = string.Format("select *from Student where stuId={0}", username);
DataTable table = DbHelper.GetDataSet(sql);
//判斷表的行數,大于等于1表示有數據,用戶存在,否則返回null
if (table.Rows.Count < 1) return null;
/*新建一個student對象 ,這里只給了三個字段進行了賦值,
* 因為我們登錄的時候,只用到了id和密碼,
* 其他時候根據需求進行賦值
*/
Student student = new Student();
student.stuId = Convert.ToInt32(table.Rows[0]["stuId"]);
student.stuName = table.Rows[0]["stuName"].ToString();
student.stuPwd = table.Rows[0]["stuPwd"].ToString();
return student;
}教師的登錄方法
private Teacher TeacherLogin(string username)
{
string sql = string.Format("select *from Teacher where tId={0}", username);
DataTable table = DbHelper.GetDataSet(sql);
//判斷表的行數,大于等于1表示有數據,用戶存在,否則返回null
if (table.Rows.Count < 1) return null;
/*新建一個student對象 ,這里只給了三個字段進行了賦值,
* 因為我們登錄的時候,只用到了id和密碼,
* 其他時候根據需求進行賦值
*/
Teacher teacher = new Teacher();
teacher.tId = Convert.ToInt32(table.Rows[0]["tId"]);
teacher.tName = table.Rows[0]["tName"].ToString();
teacher.tPWd = table.Rows[0]["tPWd"].ToString();
return teacher;
}登錄方法完成以后,我要對返回來的結果進行處理。首先判斷對象是否為null,為null就說用戶不存在。反之對象的密碼進行比較,密碼正確就彈出登錄成功,密碼不正確就提示密碼不正確。
private void btnLogin_Click(object sender, EventArgs e)
{
//獲取用戶名和密碼
string username = txtUserName.Text.Trim();
string pwd = txtPwd.Text.Trim();
if (username.Equals(""))
{
MessageBox.Show("用戶名不能為空");
return;
}
if (pwd.Equals(""))
{
MessageBox.Show("密碼不能為空");
return;
}
//管理員登錄
if (radAdmin.Checked)
{
/*為什么要返回來,因為以后處理邏輯可能在不同類里面,
* 這里只是模擬進行分層操作*/
Admin admin= AdminLogin(username);
if (admin == null)
{
MessageBox.Show("用戶不存在");
return;
}
if (!admin.adminPwd.Equals(pwd))
{
MessageBox.Show("密碼錯誤");
return;
}
}
//學生登錄
if (radStudent.Checked)
{
Student student= StudentLogin(username);
if (student == null)
{
MessageBox.Show("用戶不存在");
return;
}
if (!student.stuPwd.Equals(pwd))
{
MessageBox.Show("密碼錯誤");
return;
}
}
//教師登錄
if (radTeacher.Checked)
{
Teacher teacher= TeacherLogin(username);
if (teacher == null)
{
MessageBox.Show("用戶不存在");
return;
}
if (!teacher.tPWd.Equals(pwd))
{
MessageBox.Show("密碼錯誤");
return;
}
}
MessageBox.Show("登錄成功");
}感謝你能夠認真閱讀完這篇文章,希望小編分享的“C#中如何實現登錄功能”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關注億速云行業資訊頻道,更多相關知識等著你來學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。