如何更新DataTable的数据到数据库?
先看个范例,麻烦大家。目的是添加/删除部门用户。
首先,将所有部门名称和ID绑定到dropdownlist内(数据表Departments):
//获取所有部门
string strSql = "SELECT depID, depName FROM Departments";
SqlDataAdapter da = new SqlDataAdapter(strSql, objConnection);
DataTable dtDepartments = new DataTable();
da.Fill(dtDepartments);
DropDownList1.DataSource = dtDepartments.DefaultView;
DropDownList1.DataTextField = "depName";
DropDownList1.DataValueField = "depID";
DropDownList.DataBind();
然后,选择所有用户,绑定到CheckBoxList里面(数据表 Users):
//选择所有用户:
string strSql = "SELECT * FROM Users";
SqlDataAdapter da = new SqlDataAdapter(strSql, objConnection);
DataTable dtUsers = new DataTAble();
da.fill(dtUsers);
CheckBoxList1.DataSource = dtUsers.DefaultView;
CheckBoxList1.DataTextField = "UserName";
CheckBoxList1.DataValueField = "UserID";
CheckBoxList1.DataBind();
接着,当通过dropdownlist选择不同的部门时,根据部门编号,查询UsersInDepartment表内都有什么用户,就可以列出部门里有哪些用户了(数据表UsersInDeparmtnet):
string strSql = "SELECT userID FROM UsersInDepartment WHERE depID="+dropdownlist选中的depID;
SqlDataAdapter da = new SqlDataAdapter(strSql, objConnection);
DataTable dtUsersInDepartment = new DataTAble();
da.fill(dtUsersInDepartment);
//遍历dtUsersInDepartment,选中和CheckBoxList1项相同ID的CheckBox:
foreach(DataRow r in dtUsersInDepartment.Rows)
{
// 这里就不写了,总之就是,处于当前选中组内的用户,就打个勾。
}
好啦,然后呢,我就可以通过选中和反选中来设定部门里都有哪些用户了。
问题是,我怎么将最后的数据更新呢?我现在的办法是:
先删除UsersInDepartments 内所有 depID = dropdownlist选中的depID 项,然后根据CheckBoxList1内的选中项循环执行sp_AddUserToDepartment存储过程,遇到选中的用户,就将它插入数据库一次。也就是说,即便你将一个用户删除出部门,也要先删除所有该部门的项,然后添加进去。
最后,在下的问题是,是不是能有个更好的方法作这个操作呢?比如操作DataTable,然后更新到数据库,这个方法是否对我当前的设计适用呢?
又或者,针对目前的设计,有没有其他办法(因为系统已经用了很久了,大改动不方便)?
谢谢大家了,100分~