C#+Access 員工資訊管理--簡單的增刪改查操作和.ini配置檔案的讀寫操作。
阿新 • • 發佈:2022-04-13
1.本程式的使用的語言是C#,資料庫是Access2003。主要是對員工資訊進行簡單的增刪改查操作和對.ini配置檔案的讀寫操作。
2.程式碼執行效果如下:
功能比較簡單。其中在得到查詢結果後,在查詢結果介面上最上面的一行數字好像是根據資料庫的列數自動獲取到的,我本想把它刪掉來著,但是沒成功。
3.程式碼實現
點選檢視程式碼。clsDbOperate類--主要是資料庫連線和員工的增刪改查操作。
using System; using System.Collections.Generic; using System.Data; using System.Data.OleDb; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace UserInfoManage { public class clsDbOperate { static string exePath = System.Environment.CurrentDirectory + "\\Data\\";//資料庫在本程式中所在路徑 static string Psd = "PTC8800"; OleDbConnection conn = new OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;data source=" + exePath + "SystemData.mdb;" + "Jet OLEDB:Database Password=" + Psd); OleDbCommand oleCommand = new OleDbCommand();//操作查詢 private OleDbDataReader ole_reader = null; private DataTable dt = null; public DataTable dtSelectResult(string sql) { DataTable dt = new DataTable(); //新建表物件 try { conn.Open(); OleDbDataAdapter da = new OleDbDataAdapter(sql, conn); //建立適配物件 da.Fill(dt); //用適配物件填充表物件 conn.Close(); } catch (Exception) { } finally { conn.Close(); } return dt; } public int intSelectResultCount(string sql) { DataSet ds = new DataSet(); //新建表物件 int n = 0; try { conn.Open(); OleDbDataAdapter da = new OleDbDataAdapter(sql, conn); //建立適配物件 da.Fill(ds); //用適配物件填充表物件 n = ds.Tables[0].Rows.Count; } catch (Exception) { } finally { conn.Close(); } return n; } public int Del_Ins_Upd_Result(string sql) { int n = 0; try { conn.Open(); //增 //string sql = "insert into 表名(欄位1,欄位2,欄位3,欄位4)values(...)"; //刪 //string sql = "delete from 表名 where ="...; //改 //string sql = "update student set 欄位1=" ...; OleDbCommand comm = new OleDbCommand(sql, conn); n = comm.ExecuteNonQuery();//執行sql語句 } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { conn.Close(); } conn.Close(); return n; } /// <summary> /// 從資料庫裡面獲取資料 /// </summary> ///<param name="strSql">查詢語句 /// <returns>資料列表</returns> public DataTable GetDataTableFromDB(string strSql) { if (exePath == null) { return null; } try { conn.Open();//開啟連線 if (conn.State == ConnectionState.Closed) { return null; } oleCommand.CommandText = strSql; oleCommand.Connection = conn; ole_reader = oleCommand.ExecuteReader(CommandBehavior.Default); dt = ConvertOleDbReaderToDataTable(ref ole_reader); ole_reader.Close(); ole_reader.Dispose(); } catch (System.Exception e) { //Console.WriteLine(e.ToString()); MessageBox.Show(e.Message); } finally { if (conn.State != ConnectionState.Closed) { conn.Close(); } } return dt; } /// <summary> /// 轉換資料格式 /// </summary> ///<param name="reader">資料來源 /// <returns>資料列表</returns> private DataTable ConvertOleDbReaderToDataTable(ref OleDbDataReader reader) { DataTable dtTab = null; DataRow dr = null; int dataColumnCount = 0; int i = 0; dataColumnCount = reader.FieldCount; dtTab = BuildAndInitDataTable(dataColumnCount); dtTab.Rows.Add("序號", "工號", "姓名", "密碼", "是否管理員", "登入次數"); if (dtTab == null) { return null; } while (reader.Read()) { dr = dtTab.NewRow(); for (i = 0; i < dataColumnCount; ++i) { dr[i] = reader[i]; } dtTab.Rows.Add(dr); } return dtTab; } /// <summary> /// 建立並初始化資料列表 /// </summary> ///<param name="fieldCount">列的個數 /// <returns>資料列表</returns> private DataTable BuildAndInitDataTable(int fieldCount) { DataTable dtTab = null; DataColumn dc = null; int i = 0; if (fieldCount <= 0) { return null; } dtTab = new DataTable(); for (i = 0; i < fieldCount; ++i) { dc = new DataColumn(i.ToString()); dtTab.Columns.Add(dc); } return dtTab; } } }
點選檢視程式碼。FileOperation類--.ini配置檔案的操作類。主要是對FileConfig.ini檔案進行讀寫操作
using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; using System.Windows.Forms; using System.IO; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; namespace UserInfoManage { public class FileOperation { /// <summary> /// 寫入INI檔案 /// </summary> /// <param name="section">節點名稱[如[TypeName]]</param> /// <param name="key">鍵</param> /// <param name="val">值</param> /// <param name="filepath">檔案路徑</param> /// <returns></returns> [DllImport("kernel32")] private static extern long WritePrivateProfileString(string section, string key, string val, string filepath); /// <summary> /// 讀取INI檔案 /// </summary> /// <param name="section">節點名稱</param> /// <param name="key">鍵</param> /// <param name="def">值</param> /// <param name="retval">stringbulider物件</param> /// <param name="size">位元組大小</param> /// <param name="filePath">檔案路徑</param> /// <returns></returns> [DllImport("kernel32")] private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retval, int size, string filePath); private string strSec = ""; //INI檔名 public string ReadFile(string strFilePath, string FieldName) { string returnName = null; if (File.Exists(strFilePath))//讀取時先要判讀INI檔案是否存在 { //strSec = Path.GetFileNameWithoutExtension(strFilePath); strSec = "Information"; returnName = ContentValue(strFilePath, strSec, FieldName); } else { //MessageBox.Show("INI檔案不存在"); } return returnName; } public int WriteFile(string strFilePath, string FieldName, string FieldValue) { int ret = 0; try { //根據INI檔名設定要寫入INI檔案的節點名稱 //此處的節點名稱完全可以根據實際需要進行配置 //strSec = Path.GetFileNameWithoutExtension(strFilePath); //獲取INI檔案的節點名稱 strSec = "Information"; WritePrivateProfileString(strSec, FieldName, FieldValue.Trim(), strFilePath); ret = -1; //MessageBox.Show("寫入成功"); } catch (Exception) { } return ret; } private string ContentValue(string strFilePath, string Section, string key) //自定義函式 { StringBuilder temp = new StringBuilder(1024); GetPrivateProfileString(Section, key, "", temp, 1024, strFilePath); //對應定義的讀取函式,返回值 return temp.ToString(); } } }
點選檢視程式碼。FrmUserManager類--介面類。主要是對使用者的資訊進行操作
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using UserInfoManage; using UserInfoManage.from; using System.Runtime.InteropServices; namespace UserInfoManage { public partial class FrmUserManager : Form { private clsDbOperate dbOperate; private FileOperation fileOperation; private string strUserId; private string strUserName; private string strPassword; private string strFilePath = Application.StartupPath + @"\FileConfig.ini";//定義INI檔案的路徑 public FrmUserManager() { InitializeComponent(); } private void FrmUserManager_Load(object sender, EventArgs e) { dbOperate = new clsDbOperate(); RefreshUserInfo(); dgvUserInfo.AllowUserToAddRows = false; dgvUserInfo.SelectionMode = DataGridViewSelectionMode.FullRowSelect;//設定為整行被選中 dgvUserInfo.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill; dgvUserInfo.BackgroundColor = Color.White; dgvUserInfo.ReadOnly = true; dgvUserInfo.Columns[0].HeaderText = "序號"; dgvUserInfo.Columns[1].HeaderText = "工號"; dgvUserInfo.Columns[2].HeaderText = "姓名"; dgvUserInfo.Columns[3].HeaderText = "密碼"; dgvUserInfo.Columns[4].HeaderText = "是否管理員"; dgvUserInfo.Columns[5].HeaderText = "登入次數"; fileOperation = new FileOperation(); } /// <summary> /// 增加操作 /// </summary> private void btnAddUserInfo_Click(object sender, EventArgs e) { if (txtUserID.Text == "" || txtUserName.Text == "" || txtUserPsd.Text == "") { MessageBox.Show("員工資訊不完整,無法新增!帶*為必填項", "提示", MessageBoxButtons.OK); } else { string sql = string.Empty; string strIsAdmin = string.Empty; strIsAdmin = chkIsAdmin.Checked == true ? "1" : "0"; try { sql = "select UserName from userInfo where UserID='" + txtUserID.Text + "'"; if (dbOperate.intSelectResultCount(sql) > 0) { MessageBox.Show("已存在的員工工號!", "提示", MessageBoxButtons.OK); return; } else { sql = "insert into userInfo(UserID,UserName,UserPsd,IsAdmin,LoginTimes)"; sql += "Values('" + txtUserID.Text + "','" + txtUserName.Text + "','" + txtUserPsd.Text + "','" + strIsAdmin + "',0)"; if (dbOperate.Del_Ins_Upd_Result(sql) > 0) { RefreshUserInfo(); MessageBox.Show("新增成功!", "提示", MessageBoxButtons.OK); ClearUserInfo(); } else MessageBox.Show("新增失敗,請查詢原因", "提示", MessageBoxButtons.OK); } } catch (Exception) { MessageBox.Show("新增失敗,請查詢原因", "提示", MessageBoxButtons.OK); } } } /// <summary> /// 修改使用者資訊 /// </summary> private void btnModifyUserInfo_Click(object sender, EventArgs e) { if (txtUserID.Text == "" || txtUserName.Text == "" || txtUserPsd.Text == "") { MessageBox.Show("員工資訊不完整,無法新增!帶*為必填選項", "提示", MessageBoxButtons.OK); } else { string sql = string.Empty; string strIsAdmin = string.Empty; try { strIsAdmin = chkIsAdmin.Checked == true ? "1" : "0"; sql = "update userInfo set UserID='" + txtUserID.Text + "',UserName='" + txtUserName.Text + "',UserPsd='" + txtUserPsd.Text + "',IsAdmin='" + strIsAdmin + "'"; sql += " where UserID='" + txtUserID.Text + "'"; if (dbOperate.Del_Ins_Upd_Result(sql) > 0) { RefreshUserInfo(); MessageBox.Show("修改成功", "提示", MessageBoxButtons.OK); ClearUserInfo(); } else MessageBox.Show("修改失敗,請查詢原因", "提示", MessageBoxButtons.OK); } catch (Exception) { MessageBox.Show("修改失敗,請查詢原因", "提示", MessageBoxButtons.OK); } } } /// <summary> /// 刪除使用者資訊 /// </summary> private void btnDelUserInfo_Click(object sender, EventArgs e) { if (txtUserID.Text == "" || txtUserName.Text == "") { MessageBox.Show("請選擇要刪除的記錄", "提示", MessageBoxButtons.OK); } else { if (MessageBox.Show("確定要刪除該員工資訊嗎?\n" + "員工賬號:" + txtUserID.Text + "\n" + "員工姓名:" + txtUserName.Text, "刪除前確認", MessageBoxButtons.YesNo) == DialogResult.Yes) { try { string sql = "select * from userInfo where UserID='" + txtUserID.Text + "' and UserName='" + txtUserName.Text + "'"; if (dbOperate.intSelectResultCount(sql) > 0) { sql = "delete from UserInfo where UserID='" + txtUserID.Text + "' and UserName='" + txtUserName.Text + "'"; dbOperate.Del_Ins_Upd_Result(sql); RefreshUserInfo(); MessageBox.Show("刪除成功", "提示", MessageBoxButtons.OK); ClearUserInfo(); } else MessageBox.Show("刪除失敗,資料庫中無此員工資訊", "提示", MessageBoxButtons.OK); } catch (Exception) { MessageBox.Show("刪除失敗,請查詢原因", "提示", MessageBoxButtons.OK); } } } } private void txtUserID_KeyPress(object sender, KeyPressEventArgs e) { if (!(char.IsNumber(e.KeyChar)) && e.KeyChar != (char)8) { e.Handled = true; } } /// <summary> /// 重新整理使用者資訊 /// </summary> private void RefreshUserInfo() { string sql = "select * from userInfo"; DataTable dt = dbOperate.dtSelectResult(sql); dgvUserInfo.DataSource = dt; } /// <summary> /// 清除使用者資訊 /// </summary> private void ClearUserInfo() { txtUserID.Text = ""; txtUserName.Text = ""; txtUserPsd.Text = ""; chkIsAdmin.Checked = false; } private void dgvUserInfo_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { if (e.ColumnIndex == 3) { if (e.Value != null && e.Value.ToString().Length > 0) { e.Value = new string('*', e.Value.ToString().Length); } } if (e.ColumnIndex == 4) { if (e.Value.Equals("1")) { e.Value = "是"; } else e.Value = "否"; } } private void dgvUserInfo_CellClick(object sender, DataGridViewCellEventArgs e) { try { txtUserID.Text = dgvUserInfo.Rows[e.RowIndex].Cells[1].Value.ToString(); txtUserName.Text = dgvUserInfo.Rows[e.RowIndex].Cells[2].Value.ToString(); txtUserPsd.Text = dgvUserInfo.Rows[e.RowIndex].Cells[3].Value.ToString(); chkIsAdmin.Checked = dgvUserInfo.Rows[e.RowIndex].Cells[4].Value.ToString() == "1" ? true : false; } catch (Exception) { } } public DataTable dt; private void btnSelect_Click(object sender, EventArgs e) { if(cboSelectItems.SelectedIndex == 0) { if (txtSelectContent.Text == "") { MessageBox.Show("請輸入要查詢的使用者ID"); return; } else { /*string sql = "select * from userInfo where UserID='" + txtSelectContent.Text + "'"; dt = new DataTable(); dt = dbOperate.GetDataTableFromDB(sql); //查詢資訊介面 SelectInfo selectInfo = new SelectInfo(dt); //selectInfo.ShowDialog(); selectInfo.Show(this);*/ string sql = "select * from userInfo where UserID='" + txtSelectContent.Text + "'"; if (dbOperate.intSelectResultCount(sql) > 0) { dt = new DataTable(); dt = dbOperate.GetDataTableFromDB(sql); //查詢資訊介面 SelectInfo selectInfo = new SelectInfo(dt); //selectInfo.ShowDialog(); selectInfo.Show(this); } else { MessageBox.Show("查無此人", "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } } else { if (txtSelectContent.Text == "") { MessageBox.Show("請輸入要查詢的使用者姓名"); return; } else { string sql = "select * from userInfo where UserName= '" + txtSelectContent.Text + "'"; if (dbOperate.intSelectResultCount(sql) > 0) { dt = new DataTable(); dt = dbOperate.GetDataTableFromDB(sql); SelectInfo selectInfo = new SelectInfo(dt); //selectInfo.ShowDialog(); selectInfo.Show(this); } else { MessageBox.Show("查無此人", "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } } } /// <summary> /// 將員工資訊寫入FileConfig.ini配置檔案 /// </summary> private void btnWrite_Click(object sender, EventArgs e) { if ((txtUserID.Text.Trim() != "") && (txtUserName.Text.Trim() != "") && txtUserPsd.Text.Trim() != "") { int ret; ret = fileOperation.WriteFile(strFilePath, "UserID", txtUserID.Text); ret = fileOperation.WriteFile(strFilePath, "UserName", txtUserName.Text); ret = fileOperation.WriteFile(strFilePath, "UserPsd", txtUserPsd.Text); if (ret == -1) { MessageBox.Show("儲存成功", "提示", MessageBoxButtons.OK); } else { MessageBox.Show("儲存失敗", "提示", MessageBoxButtons.OK); } } else { MessageBox.Show("工號或姓名不能為空", "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } /// <summary> /// 將員工資訊從FileConfig.ini檔案中讀出 /// </summary> private void btnRead_Click(object sender, EventArgs e) { strUserId = fileOperation.ReadFile(strFilePath, "UserID"); strUserName = fileOperation.ReadFile(strFilePath, "UserName"); strPassword = fileOperation.ReadFile(strFilePath, "UserPsd"); txtUserID.Text = strUserId; txtUserName.Text = strUserName; txtUserPsd.Text = strPassword; } } }
點選檢視程式碼。SelectInfo類--查詢結果的介面。主要用來顯示查詢到的使用者資訊。這裡根據個人需要,如果不需要重新新建一個幾面來顯示查詢到的資訊,則可以把介面裡面的DataGridView放到FrmUserManager類中。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace UserInfoManage.from {
public partial class SelectInfo : Form {
private DataTable dt;
public SelectInfo(DataTable dt) {
InitializeComponent();
this.dt = dt;
}
private void SelectInfo_Load(object sender, EventArgs e) {
dgvSelectInfo.DataSource = dt;
}
private void dgvSelectInfo_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) {
if (e.ColumnIndex == 3 && e.RowIndex != 0) {
if (e.Value != null && e.Value.ToString().Length > 0) {
e.Value = new string('*', e.Value.ToString().Length);
}
}
if (e.ColumnIndex == 4) {
if (e.Value.Equals("1")) {
e.Value = "是";
} else {
e.Value = "否";
}
}
}
}
}