父窗体的代码:

扩展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. AWT和Swing的关系

    1.AWT和Swing都是java中的包. 2.AWT(Abstract Window Toolkit):抽象窗口工具包,早期编写图形界面应用程序的包,AWT是通过调用操作系统的native方法实现的 ...

  2. 逆向安全基础之IDA使用简介

    转载:http://m.blog.csdn.net/ilnature2008/article/details/54912854 IDA简介 IDA是业界一个功能十分强大的反汇编工具,是安全渗透人员进行 ...

  3. 你真的懂 ajax 吗?

    前言 总括: 本文讲解了ajax的历史,工作原理以及优缺点,对XMLHttpRequest对象进行了详细的讲解,并使用原生js实现了一个ajax对象以方便日常开始使用. damonare的ajax库: ...

  4. python(十四)新式类和旧式类

    这里有个重要概念呢在下面那个链接 http://blog.csdn.net/zimou5581/article/details/53053775 http://www.cnblogs.com/btch ...

  5. mongodb系列~关于双活状态的mongodb集群

    一简介:说说我们异地双活的集群 二 背景:需要建立异地双活的架构 三 构建 1 需要保证第二机房至少两个副本集DB,这样在第一机房挂掉后才能保证第二机房的可用性 2 集群状态下第二机房启用config ...

  6. RunLoop 原理和核心机制

    搞iOS之后一直没有深入研究过RunLoop,非常的惭愧.刚好前一阵子负责性能优化项目,需要利用RunLoop做性能优化和性能检测,趁着这个机会深入研究了RunLoop的原理和特性. RunLoop的 ...

  7. Python中的exec、eval使用实例

    Python中的exec.eval使用实例 这篇文章主要介绍了Python中的exec.eval使用实例,本文以简洁的方式总结了Python中的exec.eval作用,并给出实例,需要的朋友可以参考下 ...

  8. GHOST分区丢失只剩C盘

    很多人装系统时会经常会使用GHOST来恢复自己的系统,当WINDOWS系统出现意外时,再用GHOST的“From Image to 分区”来对系统进行恢复,这样就可以省去繁琐耗时的重新安装操作系统的工 ...

  9. mysql系列二、mysql内部执行过程

    向MySQL发送一个请求的时候,MySQL到底做了什么 客户端发送一条查询给服务器. 服务器先检查查询缓存,如果命中了缓存,则立刻返回存储在缓存中的结果.否则进入下一阶段. 服务器端进行SQL解析.预 ...

  10. Python3学习笔记08-tuple

    元组与列表类似,不同之处在于元组的元素不能修改 元组使用小括号,列表使用方括号 元组创建很简单,只需要在括号中添加元素,并使用逗号隔开即可 tup1 = ('Google', 'Runoob', 19 ...