C/S權限系統(一)
阿新 • • 發佈:2017-10-08
ati 臨時 day adapt 通用 lda pri userinfo selected
父窗體的代碼:
擴展Enter鍵相當於Tab鍵的思路:
1.創建 窗體的父類
2.在父類中重寫Form中的ProcessCmdKey方法,在相關控件上按回車鍵相當於按了Tab 鍵
3.讓窗體繼承新建的窗體父類,共享父類的功能方法
#region 處理窗體上的Enter鍵--在非Button、Grid控件上Enter鍵相當於Tab鍵 protected override bool ProcessCmdKey(ref Message msg,Keys keyData) { string acString = this.ActiveControl.GetType().ToString(); if (acString != "System.Windows.Forms.Button" && acString != "DevExpress.XtraEditors.SimpleButton" && acString.IndexOf("System.Windows.Forms.DataGrid") < 0 && acString.IndexOf(" DevExpress.XtraGrid") < 0) { if (keyData == Keys.Enter) { SelectNextControl(this.ActiveControl, true, true, true, true); return true; } else { return base.ProcessCmdKey(ref msg, keyData); } } else { return base.ProcessCmdKey(ref msg, keyData); } } #endregion #region 消息處理方法集 private const string topicTitle = "提示"; private const string warningTitle = "警告"; private const string errorTitle = "錯誤"; private const string successTitle = "成功"; private const string questionTitle = "請選擇"; /// <summary> /// 提示框 /// </summary> /// <param name="message"></param> public void ShowTopic(string message) { MessageBox.Show(message, topicTitle, MessageBoxButtons.OK, MessageBoxIcon.Information); } /// <summary> /// 警告框 /// </summary> /// <param name="message"></param> public void ShowWarning(string message) { MessageBox.Show(message, warningTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning); } /// <summary> /// 錯誤框 /// </summary> /// <param name="message"></param> public void ShowError(string message) { MessageBox.Show(message, errorTitle, MessageBoxButtons.OK, MessageBoxIcon.Error); } /// <summary> /// 成功框 /// </summary> /// <param name="message"></param> public void ShowSucess(string message) { MessageBox.Show(message, successTitle, MessageBoxButtons.OK, MessageBoxIcon.Information); } /// <summary> /// 選擇框 /// </summary> /// <param name="message"></param> public DialogResult ShowQuestion(string message) { return MessageBox.Show(message, questionTitle, MessageBoxButtons.YesNo, MessageBoxIcon.Question); } #endregion #region 綁定搜索組合框的通用方法 protected void BindSearchComboBox(SeachComboBox scb, DataTable source, string displayItem, string valueItem, string rowFilterExp, string sortColumn) { scb.DataSource = source; scb.DisplayItem = displayItem; scb.ValueItem = valueItem; scb.RowFilterExpression = rowFilterExp; scb.SortColumnName = sortColumn; } #endregion
用戶信息CRUD 的代碼:
public partial class FrmUserManager : FrmUIBase { public FrmUserManager() { InitializeComponent(); } //全局變量創建等待條 WaitDialogForm wdf = new WaitDialogForm("正在努力加載中....."); #region 事件代碼 private void FrmUserManager_Load(object sender, EventArgs e) { this.BindAllUsers(); } private void btnAdd_Click(object sender, EventArgs e) { AddUsers(); } private void btnDel_Click(object sender, EventArgs e) { this.DeleteUser(); } private void btnEdit_Click(object sender, EventArgs e) { GetEditUserId(); } private void btnSearch_Click(object sender, EventArgs e) { SearchInfoByCondition(); } private void btnPrint_Click(object sender, EventArgs e) { } #endregion #region 綁定用戶信息 private void BindAllUsers() { GetUsers(""); } private void GetUsers(string strWhere = "") { try { wdf.Show(); //調用業務邏輯層取數據 List<Accounts_User> aus = Accounts_UsersManager.GetAllUsers(strWhere); //顯示數據 this.gcUsers.DataSource = aus; //去掉分組面板 this.grvUsers.OptionsView.ShowPreview = false; wdf.Hide(); } catch (Exception ex) { //顯示異常信息 this.ShowError(ex.Message); } } #endregion #region 刪除用戶信息 private void DeleteUser() { try { //1.得到要刪除的用戶的編號 Accounts_User au = this.grvUsers.GetRow(this.grvUsers.GetSelectedRows()[0]) as Accounts_User; DialogResult dr = this.ShowQuestion("您確定要刪除選中的用戶【" + au.RealName + "】的信息嗎"); if (dr == System.Windows.Forms.DialogResult.Yes) { int iret = Accounts_UsersManager.DeleteUser(au.UserID); if (iret == 1) { this.ShowSucess("刪除成功!"); this.BindAllUsers();//重新綁定數據 } } } catch (Exception ex) { this.ShowError(ex.Message); } } #endregion #region 增加用戶信息 private void AddUsers() { FrmUserEdit frm = new FrmUserEdit(); //把當窗體賦值另外一個窗體的變量 // frm.frm = this; //只是把方法賦值給另外一個窗體的指針(委托) frm.at = this.BindAllUsers; frm.ShowDialog(); } #endregion #region 查詢和顯示要編輯的用戶的編號 private void GetEditUserId() { //1.得到要編輯的用戶的編號 Accounts_User au = this.grvUsers.GetRow(this.grvUsers.GetSelectedRows()[0]) as Accounts_User; if (au != null) { FrmUserEdit frm = new FrmUserEdit(); frm.userId = au.UserID; frm.at = this.BindAllUsers; frm.ShowDialog(); } } #endregion #region 查詢數據 private void SearchInfoByCondition() { string strCondition = string.Format(" and [UserName] like ‘%{0}%‘ or [RealName] like ‘%{0}%‘", this.txtSearch.Text.Trim()); this.GetUsers(strCondition); } #endregion }
Dal層:
//根據用戶名查詢用戶信息 public static DataSet GetUserInfoByUserName(string userName) { #region 拼接sql語句 // //1.建立數據庫的連擊 // string connString = ConfigurationManager.ConnectionStrings["Permissions"].ToString(); // //2.根據連擊字符串創建連接對象 // SqlConnection conn = new SqlConnection(connString); // try // { // //要執行的Sql // string sql = string.Format(@"select * from [dbo].[Accounts_Users] // where UserName=‘{0}‘", userName); // //3.打開連擊 // conn.Open(); // //執行sql語句取數據 // SqlCommand cmd = new SqlCommand(sql, conn); // //取數據到內存倉庫 // SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd); // //創建一個臨時倉庫 // DataSet ds = new DataSet(); // dataAdapter.Fill(ds); // //返回取到的數據 // return ds.Tables[0]; // } // catch (Exception ex) // { // throw ex; // } // finally // { // //關閉連擊 // conn.Close(); // } #endregion try { // string sql = string.Format(@"select * from [dbo].[Accounts_Users] // where UserName=‘{0}‘", userName); // return SqlHelper.ExecuteDataset(SqlHelper.connString, CommandType.Text, sql, null); //參數化的sql語句 // string sql = @"select * from [dbo].[Accounts_Users] // where [UserName][email protected]"; // SqlParameter para=new SqlParameter("@UserName",userName); // return SqlHelper.ExecuteDataset(SqlHelper.connString, CommandType.Text, sql, para); string spName = "usp_GetUserInfoByUserNames"; string[] values = new string[] { userName }; return SqlHelper.ExecuteDataset(SqlHelper.connString, spName, values); } catch (Exception ex) { throw ex; } } #region 查詢所有的用戶信息 /// <summary> /// 查詢所有的用戶信息 /// </summary> /// <returns>用戶信息的泛型集合</returns> public static List<Accounts_User> GetAllUsers(string strWhere = "") { try { #region sql語句 string sql = @"select * from [dbo].[Accounts_Users] where 1=1 " + strWhere; #endregion #region 用sqlhelper執行SQL語句 using (DataSet ds = SqlHelper.ExecuteDataset(SqlHelper.connString , CommandType.Text, sql, null)) { if (ds.Tables.Count > 0) { DataTable dt = ds.Tables[0]; //用來存放用戶信息的泛型集合 List<Accounts_User> aus = new List<Accounts_User>(); //通過循環把表中每一行數據轉換一個實體 foreach (DataRow dr in dt.Rows) {//每循環一次就會創建一個實體對象 Accounts_User au = new Accounts_User(); if (dr["AddTime"].ToString() != "") { au.AddTime = DateTime.Parse(dr["AddTime"].ToString()); } if (dr["Birthday"].ToString() != "") { au.Birthday = DateTime.Parse(dr["Birthday"].ToString()); } //在取用戶信息時根據用戶表的部門編號 得到對應的部門信息 au.Department = Accounts_DepartmentsService.GetDepartmentByDtId(dr["DepartmentID"].ToString()); au.Email = dr["Email"].ToString(); au.IsDel = bool.Parse(dr["IsDel"].ToString()); au.Password = dr["Password"].ToString(); au.Phone = dr["Phone"].ToString(); au.RealName = dr["RealName"].ToString(); au.Sex = dr["Sex"].ToString(); au.UserID = int.Parse(dr["UserID"].ToString()); au.UserName = dr["UserName"].ToString(); au.HeaderImage = dr["HeaderImage"].ToString(); aus.Add(au); } return aus; } } #endregion return null; } catch (Exception ex) { throw ex; } } #endregion #region 查詢一個用戶信息 /// <summary> /// 查詢一個用戶信息 /// </summary> /// <returns>查詢到的用戶對象</returns> public static Accounts_User GetOneUser(int? userId) { try { #region sql語句 string sql = string.Format(@"select * from [dbo].[Accounts_Users] where UserID =‘{0}‘", userId); #endregion #region 用sqlhelper執行SQL語句 using (SqlDataReader reader = SqlHelper.ExecuteReader(SqlHelper.connString , CommandType.Text, sql, null)) { if (reader.Read()) { Accounts_User au = new Accounts_User(); if (reader["AddTime"].ToString() != "") { au.AddTime = DateTime.Parse(reader["AddTime"].ToString()); } if (reader["Birthday"].ToString() != "") { au.Birthday = DateTime.Parse(reader["Birthday"].ToString()); } //在取用戶信息時根據用戶表的部門編號 得到對應的部門信息 au.Department = Accounts_DepartmentsService.GetDepartmentByDtId(reader["DepartmentID"].ToString()); au.Email = reader["Email"].ToString(); au.IsDel = bool.Parse(reader["IsDel"].ToString()); au.Password = reader["Password"].ToString(); au.Phone = reader["Phone"].ToString(); au.RealName = reader["RealName"].ToString(); au.Sex = reader["Sex"].ToString(); au.UserID = int.Parse(reader["UserID"].ToString()); au.UserName = reader["UserName"].ToString(); return au; } } #endregion return null; } catch (Exception ex) { throw ex; } } #endregion #region 增加用戶信息 /// <summary> /// 增加用戶信息 /// <param name="usr">用戶實體</param> /// </summary> public static int AddUser(Accounts_User usr) { try { #region sql準備 string sql = string.Format(@" INSERT INTO [dbo].[Accounts_Users] ([UserName] ,[Password],[RealName],[Sex] ,[Birthday] ,[Phone] ,[Email] ,[DepartmentID] ,[IsDel] ,[AddTime]) VALUES (‘{0}‘ ,‘{1}‘ ,‘{2}‘ ,‘{3}‘ ,‘{4}‘ ,‘{5}‘ ,‘{6}‘ ,‘{7}‘ ,‘{8}‘ ,‘{9}‘)", usr.UserName, usr.Password, usr.RealName, usr.Sex, usr.Birthday, usr.Phone, usr.Email, usr.Department.depId, usr.IsDel, usr.AddTime); #endregion #region 通過sqlHelper執行增加操作 return SqlHelper.ExecuteNonQuery(SqlHelper.connString, CommandType.Text , sql, null); #endregion } catch (Exception ex) { throw ex; } } #endregion #region 刪除用戶信息 /// <summary> /// 刪除用戶信息 /// <param name="userId">用戶編號</param> /// </summary> public static int DeleteUser(int userId) { try { #region sql準備 string sql = string.Format(@"delete from [dbo].[Accounts_Users] where UserID = ‘{0}‘", userId); #endregion #region 通過sqlHelper執行增加操作 return SqlHelper.ExecuteNonQuery(SqlHelper.connString, CommandType.Text , sql, null); #endregion } catch (Exception ex) { throw ex; } } #endregion #region 修改用戶信息 /// <summary> /// 修改用戶信息 /// <param name="usr">用戶實體</param> /// </summary> public static int EditUser(Accounts_User usr) { try { #region sql準備 string sql = string.Format(@" UPDATE [dbo].[Accounts_Users] SET [UserName] = ‘{0}‘ ,[Password] = ‘{1}‘ ,[RealName] = ‘{2}‘ ,[Sex] = ‘{3}‘ ,[Birthday] = ‘{4}‘ ,[Phone] = ‘{5}‘ ,[Email] = ‘{6}‘ ,[DepartmentID] = ‘{7}‘ ,[IsDel] = ‘{8}‘ ,[AddTime] = ‘{9}‘ WHERE [UserID] =‘{10}‘", usr.UserName, usr.Password, usr.RealName, usr.Sex, usr.Birthday, usr.Phone, usr.Email, usr.Department.depId, usr.IsDel, usr.AddTime, usr.UserID); #endregion #region 通過sqlHelper執行增加操作 return SqlHelper.ExecuteNonQuery(SqlHelper.connString, CommandType.Text , sql, null); #endregion } catch (Exception ex) { throw ex; } } #endregion
業務邏輯層:
public class Accounts_UsersManager { //實現系統登錄 public static bool Login(string strLoginName, string strLoginPwd) { try { //1.調用數據訪問層:根據用戶名得到用戶信息 DataSet dsUser = Accounts_UsersService.GetUserInfoByUserName(strLoginName); DataTable dtUser = dsUser.Tables[0]; if (dtUser.Rows.Count > 0) { DataRow drUser = dtUser.Rows[0]; //2.把用戶信息中的密碼與表示層的密碼進行對比 if (drUser["Password"].Equals(strLoginPwd)) { //密碼正確 return true; } else { return false; } } else { //用戶名不正確 return false; } } catch (Exception ex) { throw ex; //出現的問題拋給表示層 } } /// <summary> /// 查詢所有的用戶信息 /// </summary> /// <returns>用戶信息的泛型集合</returns> public static List<Accounts_User> GetAllUsers(string strWhere = "") { try { return Accounts_UsersService.GetAllUsers(strWhere); } catch (Exception ex) { //拋出異常(表示層) throw ex; } } #region 業務三:增加用戶信息 /// <summary> /// 增加用戶信息 /// <param name="usr">用戶實體</param> /// </summary> public static int AddUser(Accounts_User usr) { try { return Accounts_UsersService.AddUser(usr); } catch (Exception ex) { throw ex; } } #endregion #region 業務四:刪除用戶信息 /// <summary> /// 刪除用戶信息 /// <param name="userId">用戶編號</param> /// </summary> public static int DeleteUser(int userId) { try { return Accounts_UsersService.DeleteUser(userId); } catch (Exception ex) { throw ex; } } #endregion #region 業務五:查詢一個用戶信息 /// <summary> /// 查詢一個用戶信息 /// </summary> /// <returns>查詢到的用戶對象</returns> public static Accounts_User GetOneUser(int? userId) { try { return Accounts_UsersService.GetOneUser(userId); } catch (Exception ex) { throw ex; } } #endregion #region 業務六:修改用戶信息 /// <summary> /// 修改用戶信息 /// <param name="usr">用戶實體</param> /// </summary> public static int EditUser(Accounts_User usr) { try { return Accounts_UsersService.EditUser(usr); } catch (Exception ex) { throw ex; } } #endregion }
修改的代碼(UI):
public partial class FrmUserEdit : FrmUIBase { #region 全局變量 //FrmUserManager 窗體的實體 public FrmUserManager frm = null; //指向FrmUserManager 窗體中的BindeUsers方法的指針 public Action at = null; //要修改的用戶編號 public int? userId = null; //保存要修改的用戶對象 private Accounts_User auEdit = null; #endregion public FrmUserEdit() { InitializeComponent(); } private void FrmUserAdd_Load(object sender, EventArgs e) { this.BindDeps(); GetEditUserInfo(); this.ActiveControl = this.txtUserName; } private void btnCancel_Click(object sender, EventArgs e) { } private void scbBuMen_SelectValueChanged(object sender, EventArgs e) { //if (this.scbBuMen.SelectValue != null) //{ // string buMenName = this.scbBuMen.GetCurrentSpecialColumnValue("部門編號").ToString(); // this.txtUserName.Text = buMenName; //} } private void btnEdit_Click(object sender, EventArgs e) { if (ValidateInput()) { if (userId == null) { this.AddUser(); } else { this.EidtUser(); } } } #region 綁定部門信息 //private void BindDeps() //{ // try // { // List<Accounts_Department> ads = Accounts_DepartmentManager.GetDepartments(); // this.cboBuMen.DataSource = ads; // this.cboBuMen.DisplayMember = "depName"; // this.cboBuMen.ValueMember = "depId"; // } // catch (Exception ex) // { // this.ShowError(ex.Message); // } //} private void BindDeps() { //隱藏不需要顯示的列 ArrayList listHideColumns = new ArrayList(); listHideColumns.Add("depPid"); listHideColumns.Add("depRemark"); listHideColumns.Add("depIsDel"); listHideColumns.Add("depAddTime"); this.scbBuMen.HideCoolumnsList = listHideColumns; //取出所有的部門信息 DataTable dt = new DataTable(); dt = Accounts_DepartmentManager.GetDepartmentsToTable(); //設置中文別名 dt.Columns["depId"].ColumnName = "部門編號"; dt.Columns["depName"].ColumnName = "部門名稱"; dt.Columns["PinYin"].ColumnName = "拼音簡寫"; dt.Columns["WuBi"].ColumnName = "五筆簡寫"; string exp = "拼音簡寫 " + " like ‘*{0}*‘ or " + " 部門名稱 " + " like ‘*{0}*‘ or" + " 五筆簡寫 " + " like ‘*{0}*‘ "; ; BindSearchComboBox(this.scbBuMen, dt, "部門名稱", "部門編號", exp, "部門編號"); } #endregion #region 添加用戶信息 private void AddUser() { try { //創建一個要增加的實體類 Accounts_User usr = new Accounts_User(); usr.AddTime = DateTime.Now; usr.Birthday = this.dtpBirthDay.Value; //在增加用戶信息時外鍵對象如何處理 usr.Department = new Accounts_Department(); usr.Department.depId = this.scbBuMen.GetCurrentSpecialColumnValue("部門編號").ToString(); usr.Email = this.txtEmail.Text; usr.IsDel = this.chkEnabled.Checked ? true : false; usr.Password = this.txtPassword.Text; usr.Phone = this.txtPhone.Text; usr.RealName = this.txtRealname.Text; usr.Sex = this.cboGender.Text; usr.UserName = this.txtUserName.Text; //調用業務邏輯層的增加用戶信息的方法 int iret = Accounts_UsersManager.AddUser(usr); if (iret == 1) { this.ShowTopic("增加成功!"); //調用實例 中的方法 // frm.BindUsers(); //調用指針指向的方法 at(); if (this.chkClose.Checked) { this.Close(); } this.ClearControls(); } } catch (Exception ex) { this.ShowError(ex.Message); } } #endregion #region 非空驗證 private bool ValidateInput() { if(this.txtUserName.Text.Trim().Equals(string.Empty)) { MessageBox.Show("用戶名不能為空!"); this.txtUserName.Focus(); this.ActiveControl = this.txtUserName; return false; } if (this.txtRealname.Text.Trim().Equals(string.Empty)) { MessageBox.Show("真實姓名不能為空!"); this.txtRealname.Focus(); this.ActiveControl = this.txtRealname; return false; } if (this.cboGender.Text.Trim().Equals(string.Empty)) { MessageBox.Show("性別不能為空!"); this.cboGender.Focus(); this.ActiveControl = this.cboGender; return false; } if (this.scbBuMen.SelectValue == null) { MessageBox.Show("所屬部門不能為空不能為空!"); this.scbBuMen.Focus(); this.ActiveControl = this.scbBuMen; return false; } if (this.txtPassword.Text.Trim().Equals(string.Empty) || this.txtConfirmPassword.Text.Trim().Equals(string.Empty)) { MessageBox.Show("密碼框不能為空!"); this.txtPassword.Focus(); this.ActiveControl = this.txtPassword; return false; } if (!this.txtPassword.Text.Trim().Equals(this.txtConfirmPassword.Text.Trim())) { MessageBox.Show("兩次密碼輸入不一致!"); this.txtConfirmPassword.Text = ""; this.txtPassword.Text = ""; this.txtPassword.Focus(); this.ActiveControl = this.txtPassword; return false; } return true; } #endregion #region 清空輸入控件 private void ClearControls() { try { foreach (Control control in this.grbOperatorAdd.Controls) { if (control.GetType().ToString().Equals("DevExpress.XtraEditors.TextEdit")) { (control as DevExpress.XtraEditors.TextEdit).Text = ""; } if (control.GetType().ToString().Equals("System.Windows.Forms.ComboBox")) { (control as System.Windows.Forms.ComboBox).Text = ""; } if (control.GetType().ToString().Equals("MyController.SeachComboBox")) { (control as MyController.SeachComboBox).Text = ""; } } } catch (Exception ex) { this.ShowError(ex.Message); } } #endregion #region 根據用戶編號得到用戶信息 private void GetEditUserInfo() { if (userId != null) { try { auEdit = Accounts_UsersManager.GetOneUser(userId); this.txtConfirmPassword.Text = auEdit.Password; this.txtEmail.Text = auEdit.Email; this.txtPassword.Text = auEdit.Password; this.txtPhone.Text = auEdit.Phone; this.txtRealname.Text = auEdit.RealName; this.txtUserName.Text = auEdit.UserName; this.cboGender.Text = auEdit.Sex; this.dtpBirthDay.Value = auEdit.Birthday.Year < 9 ? DateTime.Now : auEdit.Birthday; this.scbBuMen.SetSelectedItem(auEdit.Department.depId); this.Text = "修改用戶信息"; this.btnEdit.Text = "修改"; } catch (Exception ex) { this.ShowError(ex.Message); } } else { this.Text = "新增用戶信息"; this.btnEdit.Text = "增加"; } } #endregion #region 修改用戶信息 private void EidtUser() { try { auEdit.AddTime = DateTime.Now; auEdit.Birthday = this.dtpBirthDay.Value; //在增加用戶信息時外鍵對象如何處理 auEdit.Department = new Accounts_Department(); auEdit.Department.depId = this.scbBuMen.GetCurrentSpecialColumnValue("部門編號").ToString(); auEdit.Email = this.txtEmail.Text; auEdit.IsDel = this.chkEnabled.Checked ? true : false; auEdit.Password = this.txtPassword.Text; auEdit.Phone = this.txtPhone.Text; auEdit.RealName = this.txtRealname.Text; auEdit.Sex = this.cboGender.Text; auEdit.UserName = this.txtUserName.Text; //調用業務邏輯層的增加用戶信息的方法 int iret = Accounts_UsersManager.EditUser(auEdit); if (iret == 1) { this.ShowTopic("修改成功!"); //調用實例 中的方法 // frm.BindUsers(); //調用指針指向的方法 at(); this.Close(); } } catch (Exception ex) { this.ShowError(ex.Message); } } #endregion }
角色CRUD代碼:(UI)
public partial class FrmRoleManager : FrmUIBase { public FrmRoleManager() { InitializeComponent(); } #region 事件列表 private void btnAdd_Click(object sender, EventArgs e) { AddRole(); } private void FrmRoleManager_Load(object sender, EventArgs e) { this.BindAllRoles(); } private void btnDel_Click(object sender, EventArgs e) { this.DeleteRole(); } private void btnEdit_Click(object sender, EventArgs e) { GetEditRoleId(); } private void btnSearch_Click(object sender, EventArgs e) { SearchInfoByCondition(); } #endregion #region 功能列表 #region 綁定角色信息 private void BindAllRoles() { GetRoles(""); } private void GetRoles(string strWhere = "") { try { //顯示滾動條 WaitDialogForm wdf = new WaitDialogForm("正在努力加載中......"); wdf.Show(); //調用業務邏輯層取數據 List<Accounts_Role> aus = Accounts_RolesManager.GetAllRoles(strWhere); //顯示數據 this.gcRoles.DataSource = aus; //去掉分組面板 this.grvRoles.OptionsView.ShowGroupPanel = false; //隱藏滾動條 wdf.Close(); } catch (Exception ex) { //顯示異常信息 MessageBox.Show(ex.Message); } } #endregion #region 刪除角色信息 private void DeleteRole() { try { //1.得到要刪除的角色的編號 Accounts_Role au = this.grvRoles.GetRow(this.grvRoles.GetSelectedRows()[0]) as Accounts_Role; DialogResult dr = this.ShowQuestion("您確定要刪除選中的角色【" + au.rName + "】的信息嗎"); if (dr == System.Windows.Forms.DialogResult.Yes) { int iret = Accounts_RolesManager.DeleteRole(au.rId); if (iret == 1) { this.ShowSucess("刪除成功!"); this.BindAllRoles();//重新綁定數據 } } } catch (Exception ex) { this.ShowError(ex.Message); } } #endregion #region 查詢和顯示要編輯的角色的編號 private void GetEditRoleId() { //1.得到要編輯的角色的編號 Accounts_Role au = this.grvRoles.GetRow(this.grvRoles.GetSelectedRows()[0]) as Accounts_Role; if (au != null) { FrmRoleEdit frm = new FrmRoleEdit(); frm.RoleId = au.rId; frm.at = this.BindAllRoles; frm.ShowDialog(); } } #endregion #region 增加角色信息 private void AddRole() { FrmRoleEdit frm = new FrmRoleEdit(); //把當窗體賦值另外一個窗體的變量 frm.frm = this; //只是把方法賦值給另外一個窗體的指針(委托) frm.at = this.BindAllRoles; frm.ShowDialog(); } #endregion #region 查詢數據 private void SearchInfoByCondition() { string strCondition = string.Format(" and [rName] like ‘%{0}%‘ or [rRemark] like ‘%{0}%‘", this.txtSearch.Text.Trim()); this.GetRoles(strCondition); } #endregion #endregion }
Dal層:
public class Accounts_RolesService { #region 查詢所有的角色信息 /// <summary> /// 查詢所有的角色信息 /// </summary> /// <returns>角色信息的泛型集合</returns> public static List<Accounts_Role> GetAllRoles(string strWhere = "") { try { #region sql語句 string sql = @"select * from [dbo].[Accounts_Roles] where 1=1 " + strWhere; #endregion #region 用sqlhelper執行SQL語句 using (DataSet ds = SqlHelper.ExecuteDataset(SqlHelper.connString , CommandType.Text, sql, null)) { if (ds.Tables.Count > 0) { DataTable dt = ds.Tables[0]; //用來存放用戶的角色信息的泛型集合 List<Accounts_Role> aus = new List<Accounts_Role>(); //通過循環把表中每一行數據轉換一個實體 foreach (DataRow dr in dt.Rows) {//每循環一次就會創建一個實體對象 Accounts_Role au = new Accounts_Role(); if (dr["rAddTime"].ToString() != "") { au.rAddTime = DateTime.Parse(dr["rAddTime"].ToString()); } au.rId = int.Parse(dr["rId"].ToString()); au.rName = dr["rName"].ToString(); au.rRemark = dr["rRemark"].ToString(); au.rIsShow = bool.Parse(dr["rIsShow"].ToString()); au.rIsDel = bool.Parse(dr["rIsDel"].ToString()); aus.Add(au); } return aus; } } #endregion return null; } catch (Exception ex) { throw ex; } } #endregion #region 查詢一個角色信息 /// <summary> /// 查詢一個角色信息 /// </summary> /// <returns>查詢到的用戶的角色對象</returns> public static Accounts_Role GetOneRole(int? roleId) { try { #region sql語句 string sql = @"select * from [dbo].[Accounts_Roles] where rId [email protected]"; SqlParameter para = new SqlParameter("@rId", roleId); #endregion #region 用sqlhelper執行SQL語句 using (SqlDataReader reader = SqlHelper.ExecuteReader(SqlHelper.connString , CommandType.Text, sql, para)) { if (reader.Read()) { Accounts_Role au = new Accounts_Role(); if (reader["rAddTime"].ToString() != "") { au.rAddTime = DateTime.Parse(reader["rAddTime"].ToString()); } au.rId = int.Parse(reader["rId"].ToString()); au.rName = reader["rName"].ToString(); au.rRemark = reader["rRemark"].ToString(); au.rIsShow = bool.Parse(reader["rIsShow"].ToString()); au.rIsDel = bool.Parse(reader["rIsDel"].ToString()); return au; } } #endregion return null; } catch (Exception ex) { throw ex; } } #endregion #region 增加角色信息 /// <summary> /// 增加角色信息 /// <param name="usr">角色實體</param> /// </summary> public static int AddRole(Accounts_Role role) { try { #region sql準備 string sql = string.Format(@" INSERT INTO [dbo].[Accounts_Roles] ([rName] ,[rRemark] ,[rIsShow] ,[rIsDel] ,[rAddTime]) VALUES (@rName ,@rRemark ,@rIsShow ,@rIsDel ,@rAddTime)"); SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@rName",role.rName), new SqlParameter("@rRemark",role.rRemark), new SqlParameter("@rIsShow",role.rIsShow), new SqlParameter("@rIsDel",role.rIsDel), new SqlParameter("@rAddTime",role.rAddTime) }; #endregion #region 通過sqlHelper執行增加操作 return SqlHelper.ExecuteNonQuery(SqlHelper.connString, CommandType.Text , sql, paras); #endregion } catch (Exception ex) { throw ex; } } #endregion #region 刪除角色信息 /// <summary> /// 刪除角色信息 /// <param name="roleId">角色編號</param> /// </summary> public static int DeleteRole(int? roleId) { try { #region sql準備 string sql = @"delete from [dbo].[Accounts_Roles] where rId [email protected]"; SqlParameter para = new SqlParameter("@rId", roleId); #endregion #region 通過sqlHelper執行增加操作 return SqlHelper.ExecuteNonQuery(SqlHelper.connString, CommandType.Text , sql, para); #endregion } catch (Exception ex) { throw ex; } } #endregion #region 修改角色信息 /// <summary> /// 修改角色信息 /// <param name="role">角色實體</param> /// </summary> public static int EditRole(Accounts_Role role) { try { #region sql準備 string sql = @" UPDATE [dbo].[Accounts_Roles] SET [rName] = @rName ,[rRemark] = @rRemark ,[rIsShow] = @rIsShow ,[rIsDel] = @rIsDel ,[rAddTime] = @rAddTime WHERE [rId]= @rId"; SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@rName",role.rName), new SqlParameter("@rRemark",role.rRemark), new SqlParameter("@rIsShow",role.rIsShow), new SqlParameter("@rIsDel",role.rIsDel), new SqlParameter("@rAddTime",role.rAddTime), new SqlParameter("@rId",role.rId) }; #endregion #region 通過sqlHelper執行增加操作 return SqlHelper.ExecuteNonQuery(SqlHelper.connString, CommandType.Text , sql, paras); #endregion } catch (Exception ex) { throw ex; } } #endregion }
BLL層:
public class Accounts_RolesManager { #region 業務一:查詢所有的角色信息 /// <summary> /// 查詢所有的角色信息 /// </summary> /// <returns>角色信息的泛型集合</returns> public static List<Accounts_Role> GetAllRoles(string strWhere = "") { try { return Accounts_RolesService.GetAllRoles(strWhere); } catch (Exception ex) { //拋出異常(表示層) throw ex; } } #endregion #region 業務三:增加角色信息 /// <summary> /// 增加角色信息 /// <param name="usr">角色實體</param> /// </summary> public static int AddRole(Accounts_Role usr) { try { return Accounts_RolesService.AddRole(usr); } catch (Exception ex) { throw ex; } } #endregion #region 業務四:刪除角色信息 /// <summary> /// 刪除角色信息 /// <param name="RoleId">角色編號</param> /// </summary> public static int DeleteRole(int RoleId) { try { return Accounts_RolesService.DeleteRole(RoleId); } catch (Exception ex) { throw ex; } } #endregion #region 業務五:查詢一個角色信息 /// <summary> /// 查詢一個角色信息 /// </summary> /// <returns>查詢到的角色對象</returns> public static Accounts_Role GetOneRole(int? RoleId) { try { return Accounts_RolesService.GetOneRole(RoleId); } catch (Exception ex) { throw ex; } } #endregion #region 業務六:修改角色信息 /// <summary> /// 修改角色信息 /// <param name="usr">角色實體</param> /// </summary> public static int EditRole(Accounts_Role usr) { try { return Accounts_RolesService.EditRole(usr); } catch (Exception ex) { throw ex; } } #endregion }
修改的代碼:(UI)
public partial class FrmRoleEdit : FrmUIBase { #region 全局變量 //FrmRoleManager窗體的實例 public FrmRoleManager frm = null; //指向FrmRoleManager窗體中的BindRoles方法指針 public Action at = null; /// <summary> /// 要修改的用戶編號 /// </summary> public int? RoleId = null; //保存要修改的用戶對象 private Accounts_Role auEdit = null; #endregion public FrmRoleEdit() { InitializeComponent(); } #region 事件列表 private void btnCancel_Click(object sender, EventArgs e) { this.Close(); } private void btnEdit_Click(object sender, EventArgs e) { if (ValidateInput()) { if (RoleId == null) { this.AddRole(); } else { this.EidtRole(); } } } private void FrmRoleEdit_Load(object sender, EventArgs e) { GetEditRoleInfo(); this.ActiveControl = this.txtRoleName; } #endregion #region 功能列表 #region 添加角色信息 private void AddRole() { try { //創建一個要增加的實體類 Accounts_Role role = new Accounts_Role(); role.rAddTime = DateTime.Now; role.rIsDel = this.chkEnabled.Checked; role.rIsShow = this.chkShow.Checked; role.rName = this.txtRoleName.Text; role.rRemark = this.txtRemark.Text; //調用業務邏輯層的增加用戶信息的方法 int iret = Accounts_RolesManager.AddRole(role); if (iret == 1) { this.ShowTopic("增加成功!"); //調用實例中的方法 //frm.BindRoles(); //調用指針指向的方法 at(); if (this.chkClose.Checked) { this.Close(); } this.ClearControls(); } } catch (Exception ex) { this.ShowError(ex.Message); } } #endregion #region 非空驗證 private bool ValidateInput() { if (this.txtRoleName.Text.Trim().Equals(string.Empty)) { MessageBox.Show("角色名不能為空!"); this.txtRoleName.Focus(); this.ActiveControl = this.txtRoleName; return false; } if (this.txtRemark.Text.Trim().Equals(string.Empty)) { MessageBox.Show("角色說明不能為空!"); this.txtRemark.Focus(); this.ActiveControl = this.txtRemark; return false; } return true; } #endregion #region 清空輸入控件 private void ClearControls() { try { foreach (Control control in this.grbOperatorAdd.Controls) { if (control.GetType().ToString().Equals("DevExpress.XtraEditors.TextEdit")) { (control as DevExpress.XtraEditors.TextEdit).Text = ""; } if (control.GetType().ToString().Equals("System.Windows.Forms.ComboBox")) { (control as System.Windows.Forms.ComboBox).Text = ""; } if (control.GetType().ToString().Equals("MyController.SeachComboBox")) { (control as MyController.SeachComboBox).Text = ""; } } } catch (Exception ex) { this.ShowError(ex.Message); } } #endregion #region 根據角色編號得到角色編號 private void GetEditRoleInfo() { if (RoleId != null) { try { auEdit = Accounts_RolesManager.GetOneRole(RoleId); this.txtRoleName.Text = auEdit.rName; this.txtRemark.Text = auEdit.rRemark; this.chkShow.Checked = auEdit.rIsShow; this.chkEnabled.Checked = auEdit.rIsDel; this.Text = "修改角色信息"; this.btnEdit.Text = "修改"; } catch (Exception ex) { this.ShowError(ex.Message); } } else { this.Text = "新增角色信息"; this.btnEdit.Text = "增加"; } } #endregion #region 修改用戶信息 private void EidtRole() { try { auEdit.rAddTime = DateTime.Now; auEdit.rIsDel = this.chkEnabled.Checked; auEdit.rIsShow = this.chkShow.Checked; auEdit.rName = this.txtRoleName.Text; auEdit.rRemark = this.txtRemark.Text; //調用業務邏輯層的增加用戶信息的方法 int iret = Accounts_RolesManager.EditRole(auEdit); if (iret == 1) { this.ShowTopic("修改成功!"); //調用實例中的方法 //frm.BindRoles(); //調用指針指向的方法 at(); this.Close(); } } catch (Exception ex) { this.ShowError(ex.Message); } } #endregion #endregion }
部門管理的代碼Dal:
public class Accounts_DepartmentsService { #region 根據部門編號得到部門信息 /// <summary> ///根據部門編號得到部門信息 /// </summary> /// <param name="id">部門編號</param> /// <returns></returns> public static Accounts_Department GetDepartmentByDtId(string id) { #region sql語句 string sql = string.Format(@"SELECT * FROM [dbo].[Accounts_Departments] where [depId] = ‘{0}‘", id); #endregion #region 根據sql語句再結合sqlhelper取數據 //創建集合來保存取出的數據 using (DataSet ds = SqlHelper.ExecuteDataset(SqlHelper.connString, CommandType.Text , sql, null)) { if (ds.Tables.Count > 0) { DataTable dt = ds.Tables[0]; Accounts_Department ad = new Accounts_Department(); foreach (DataRow dr in dt.Rows) { //每循環一次,就把把一行數據轉換成一個對象 ad.depId = dr["depId"].ToString(); ad.depPid = dr["depPid"].ToString(); ad.depName = dr["depName"].ToString(); ad.depRemark = dr["depRemark"].ToString(); ad.depIsDel = bool.Parse(dr["depIsDel"].ToString()); ad.depAddTime = DateTime.Parse(dr["depAddTime"].ToString()); } return ad; } } return null; #endregion } #endregion #region 得到所有部門信息 /// <summary> ///得到所有部門信息 /// </summary> /// <returns></returns> public static List<Accounts_Department> GetDepartments() { #region sql語句 string sql = string.Format(@"SELECT * FROM [dbo].[Accounts_Departments]"); #endregion #region 根據sql語句再結合sqlhelper取數據 //創建集合來保存取出的數據 using (DataSet ds = SqlHelper.ExecuteDataset(SqlHelper.connString, CommandType.Text , sql, null)) { if (ds.Tables.Count > 0) { DataTable dt = ds.Tables[0]; List<Accounts_Department> ads = new List<Accounts_Department>(); foreach (DataRow dr in dt.Rows) { //每循環一次,就把把一行數據轉換成一個對象 Accounts_Department ad = new Accounts_Department(); ad.depId = dr["depId"].ToString(); ad.depPid = dr["depPid"].ToString(); ad.depName = dr["depName"].ToString(); ad.depRemark = dr["depRemark"].ToString(); ad.depIsDel = bool.Parse(dr["depIsDel"].ToString()); ad.depAddTime = DateTime.Parse(dr["depAddTime"].ToString()); ads.Add(ad); } return ads; } } return null; #endregion } #endregion #region 得到所有部門信息 /// <summary> ///得到所有部門信息 /// </summary> /// <returns></returns> public static DataTable GetDepartmentsToTable() { #region sql語句 string sql = string.Format(@"select *,[dbo].[fun_getPY]([depName]) as PinYin ,[dbo].[fun_getWB]([depName]) as WuBi from [dbo].[Accounts_Departments]"); #endregion #region 根據sql語句再結合sqlhelper取數據 //創建集合來保存取出的數據 using (DataSet ds = SqlHelper.ExecuteDataset(SqlHelper.connString, CommandType.Text , sql, null)) { if (ds.Tables.Count > 0) { DataTable dt = ds.Tables[0]; return dt; } } return null; #endregion } #endregion }
Bll層:
public class Accounts_DepartmentManager { #region 得到所有部門信息 /// <summary> ///得到所有部門信息 /// </summary> /// <returns></returns> public static List<Accounts_Department> GetDepartments() { try { return Accounts_DepartmentsService.GetDepartments(); } catch (Exception ex) { throw ex; } } #endregion #region 得到所有部門信息 /// <summary> ///得到所有部門信息 /// </summary> /// <returns></returns> public static DataTable GetDepartmentsToTable() { try { return Accounts_DepartmentsService.GetDepartmentsToTable(); } catch (Exception ex) { throw ex; } } #endregion }
C/S權限系統(一)