最近碰到要实现一个功能 缓存中有张数据表 要对其进行删除 增加操作 唯有再最后点页面保存时,才将数据存放到数据库中
因此 考虑用SqlCommandBuilder来实现批量更新
下面方法简单的实现了批量删除、插入记录的功能![]()
#region 批量更新子表记录
string queryString = "Select * From ProjectManageSub Where BelongID = " + _ProjectManageMain.ID;
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = new SqlCommand(queryString, conn);
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
DataTable dt = new DataTable();
adapter.SelectCommand.Transaction = trans; //这里启用了事务
adapter.Fill(dt);
int count = adapter.Update(DT); //DT为缓存中的DataTable,对于缓存中的数据删除方法再下方
DT.AcceptChanges();
#endregion
/// <summary>
/// 删除缓存中的数据
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void gvContent_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
DT.Rows[e.RowIndex].Delete(); //Delete()方法只是对DataRowState = Delete做标志位 并不是真删除 而Dt.Rows.RemoveAt(e.RowIndex)是真删除行 这句话是关键
BindGV();
}
/// <summary>
/// 绑定GridView
/// </summary>
private void BindGV()
{
DataTable dtt = DT.Copy();
for (int i = dtt.Rows.Count - 1; i >= 0; i--)
{
if (dtt.Rows[i].RowState == DataRowState.Deleted)
{
dtt.Rows.RemoveAt(i);
}
}
gvContent.DataSource = dtt;
gvContent.DataBind();
}
以上就是全部代码
简单的运用SqlCommandBuilder
浙公网安备 33010602011771号