winform中使用BindingSource绑定到dataGridView数据源,并进行增删改操作。
private BindingSource usersbinding;//定义数据源
//查询记录事件
List
//绑定用户列表
if (usersbinding == null)
{
usersbinding = new BindingSource();
usersbinding.PositionChanged += new EventHandler(OnPositionChanged);//行点击事件,不需要可不加
UserDataGridView.DataSource = usersbinding;
}
usersbinding.SuspendBinding();
usersbinding.DataSource = data;
usersbinding.ResumeBinding();
if (usersbinding.Position == 0) OnPositionChanged(null, EventArgs.Empty);
private void OnPositionChanged(object sender, EventArgs e)
{
if (usersbinding.IsBindingSuspended) return;
//右侧详情显示
userlist user = (userlist)usersbinding.Current;
tb_userid.InputText = user.id.ToString();
//详情显示
}
//删除事件中
if(usersbinding.Current != null)
{
userlist user = (userlist)usersbinding.Current;
BLL.DeleteUser(user.id);//数据库删除
usersbinding.RemoveCurrent();//数据源删除
usersbinding.Position = 0;
}
//修改事件中
if (usersbinding.Current == null)
{
FrmDialogEx.ShowDialog(this, "请先选择用户", "确定", "信息提示");
return;
}
sysuserInfo info = new sysuserInfo();
//对象赋值
if (BLL.UpdateUser(info))
{
userlist user = (userlist)usersbinding.Current;
user.id = info.Id;
user.logname = info.LoginName;
user.password = info.PassWord;
user.roleName = info.RoleName;
user.remark = info.Remark;
user.username = info.UserName;
user.roleid = info.RoleId.ToString();
usersbinding.ResetCurrentItem();
}
//新增事件中
userlist user = new userlist();
//对象赋值
if (BLL.AddUser(user ))
{
enumbinding.Add(user );
enumbinding.ResetCurrentItem();
}