父窗体的代码:

扩展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]=@UserName";
// 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 =@rId";
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 =@rId";
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权限系统(一)的更多相关文章

  1. phpcms中的RBAC权限系统

    PHPCMS中的RBAC权限系统主要用到了4张数据表:管理员表,角色表,菜单表,菜单权限表.先来看看数据库的数据表结构: admin 管理员表 ID 字段 类型 Null 默认 索引 额外 注释 1 ...

  2. 基于资源的权限系统-API设计

    概述 权限系统需要和别的系统集成,因此,良好的API是易用性的保证. 这里只设计一些权限相关的核心 API,关于用户,组织,导入导出之类的后续再逐步补充 API 设计 围绕权限有以下 4 类 API: ...

  3. 高校手机签到系统——第一部分Authority权限系统(下)

    很抱歉,之前寝室光纤断了,所以到现在才更新这个系列的第二篇博客.点击访问高校手机签到系统——第一部分Authority权限系统(上) 这几天我反思了一下上一篇写博上的方式,一味的贴代码式的,是否应该更 ...

  4. ubuntu chmod 无法更改 文件夹权限 系统提示“不允许的操作 2、linux 如何修改只读文件 3、ubuntu安装

    1.ubuntu chmod 无法更改 文件夹权限 系统提示“不允许的操作 答案:需要超级用户权限 sudo 2.linux 如何修改只读文件 答案:可以使用chmod命令,为改文件提供其他的权限.u ...

  5. 以一个权限系统来告别WebForm —(一)项目整休架构设计与数据库设计

    在本节我想与大家与分享一下,我所将要做的权限系统的架构和数据库的表的设计.请各位大神们对我项目中设计的不足之处进行指导,让我得以更好的写完它,留给需要它的人. 我的项目架构如下图所示: 如上图所示,在 ...

  6. S2SH商用后台权限系统第二讲

    各位博友: 您好!我们今天接着上一讲继续学习S2SH商用后台权限系统,本讲我们重点设计下整个系统所需要的表结构. 用户表:记录用户信息. 角色表:标记用户归属的角色信息. 菜单表:或者叫模块表,记录整 ...

  7. S2SH商用后台权限系统第一讲

    各位博友: 您好!从今天开始我们做一套商用的权限系统.功能包含用户管理.角色管理.模块管理.权限管理.大家知道每个商用系统肯定会拥有一套后台系统,我们所讲的权限系统是整个系统核心部分.本套系统技术有s ...

  8. 权限系统与RBAC模型概述

    为了防止无良网站的爬虫抓取文章,特此标识,转载请注明文章出处.LaplaceDemon/SJQ. http://www.cnblogs.com/shijiaqi1066/p/3793894.html ...

  9. AngularJs打造一个简易权限系统

    AngularJs打造一个简易权限系统 一.引言 上一篇博文已经向大家介绍了AngularJS核心的一些知识点,在这篇博文将介绍如何把AngularJs应用到实际项目中.本篇博文将使用AngularJ ...

  10. 分享Mvc3+NInject+EF+LigerUI权限系统

    分享Mvc3+NInject+EF+LigerUI权限系统   前段时间时不时看到有园友的分享权限系统,于是本人突发奇想,也想写一个玩玩,就利用晚上时间,陆陆续续花了一周多样子,写了如今这个权限系统, ...

随机推荐

  1. 学习windows编程 day4 之 映射模式

    LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) { HDC hdc; PAINTSTRU ...

  2. CodeForces-915C Permute Digits

    C. Permute Digits time limit per test 1 second memory limit per test 256 megabytes input standard in ...

  3. Shell + crontab 实现日志压缩归档

    Shell + crontab 实现日志压缩归档 crontab # archive the ats log days. */ * * * * root /bin/>& shell #! ...

  4. Javaweb学习笔记——(三)——————JavaScript基础&DOM基础

    day031.js的String对象 **创建String对象 ***var str = "abc"; **方法和属性(文档) ***属性 lenth:字符串的长度 ***方法 ( ...

  5. QLabel-标签控件的应用

    label = QLabel('我是李明') #创建标签控件对象.参数:标签中要显示的文本 label.setText('我是明明') 修改标签控件显示的文本 self.label.text() 返回 ...

  6. 关于JS事件冒泡与JS事件代理(事件委托)

    连接:https://blog.csdn.net/supercoooooder/article/details/52190100 核心代码: <ul id="parentUl" ...

  7. SpringBoot2.X自定义拦截器实战及新旧配置对比(核心知识)

    简介: 讲解拦截器使用,Spingboot2.x新版本配置拦截拦截器和旧版本SpringBoot配置拦截器区别讲解 1.@Configuration 继承WebMvcConfigurationAdap ...

  8. Mac下的开发工具

    1.webstrom 淘宝上2块钱就能买一个 WebStorm 是jetbrains公司旗下一款JavaScript 开发工具.被广大中国JS开发者誉为“Web前端开发神器”.“最强大的HTML5编辑 ...

  9. 【转】Python之列表生成式、生成器、可迭代对象与迭代器

    [转]Python之列表生成式.生成器.可迭代对象与迭代器 本节内容 语法糖的概念 列表生成式 生成器(Generator) 可迭代对象(Iterable) 迭代器(Iterator) Iterabl ...

  10. 『PyTorch』第五弹_深入理解autograd_上:Variable属性方法

    在PyTorch中计算图的特点可总结如下: autograd根据用户对variable的操作构建其计算图.对变量的操作抽象为Function. 对于那些不是任何函数(Function)的输出,由用户创 ...