C# WindowsForm 員工管理系統一【登入】
阿新 • • 發佈:2019-01-22
原始碼下載
開發環境
Visual Studio 2015,SQL Server2012
資料庫
使用者的使用者名稱和密碼等資訊都儲存在資料庫中,先在SQL Server中建立一個數據庫命名為“Staff”,然後在其中新增一個“StaffAccount”表,新增ID Name Password UserType 欄位,並且將ID設為主鍵,標識。新增一個記錄以便測試用。
客戶端
新建一個Windows窗體應用程式,開啟檢視->工具箱可看到如下介面:
左側為工具箱,右下是屬性
從左側工具箱中找到Label,TextBox,Button
控制元件分別拖入視窗Form1中
選中任意控制元件,可在右下角屬性欄中看到該控制元件的屬性
將2個label的Text屬性設定為“使用者名稱”和“密碼”
將2個Button的Text屬性設定為”登入”,”取消”.
當然,為了窗體的美觀可以在上面加上PictureBox控制元件,匯入圖片來修飾窗體。
現在該連線資料庫了,作為全宇宙最強大的IDE–Visual Studio 為我們提供了很多簡便操作 ,點選 工具->連線到資料庫
伺服器名:127.0.0.1 注意選擇所需要連線的資料庫
完成之後可以在APP.config配置檔案中看到多出瞭如下程式碼:
<connectionStrings >
<add name="WindowsFormsApplication6.Properties.Settings.staffConnectionString"
connectionString="Data Source=127.0.0.1;Initial Catalog=staff;User ID=wwb;Password=wwb"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
右擊Form1窗體->檢視程式碼
定義全域性變數
public static string UserName;
public static string UserType;
public static int ID;
//定義連線字串
string connstr = ConfigurationManager.ConnectionStrings["WindowsFormsApplication6.Properties.Settings.staffConnectionString"].ConnectionString;
“WindowsFormsApplication6.Properties.Settings.staffConnectionString”根據APP.config 中的name值進行更改
雙擊登入按鈕 Visual Studio 會自動生成該控制元件的Click事件
private void button1_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(connstr))
{
string sql = "select Password,UserType,ID from StaffAccount where Name='" + textBox1.Text + "'";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
conn.Open();//開啟連線
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
string pwd = reader.GetString(0).Trim();
string utype = reader.GetString(1);
int id = reader.GetInt32(2);
if (pwd == textBox2.Text)
{
//儲存使用者的使用者名稱,ID,使用者型別
UserName = textBox1.Text;
UserType = utype;
ID = id;
MessageBox.Show("系統登入成功,正在跳轉主頁面...");
else {
MessageBox.Show("密碼錯誤!請再次輸入!");
textBox2.Text = "";
}
}
else
{
MessageBox.Show("使用者名稱不存在,請重新出入!");
textBox1.Text = "";
}
}
}
}
}
雙擊取消按鈕
private void button2_Click(object sender, EventArgs e)
{
textBox1.Text = "";
textBox2.Text = "";
Application.Exit();
}
執行後輸入在資料庫中增加的記錄
如果想讓密碼欄中顯示字元為星號,可以將PasswordChar屬性設定為*。