DataTable中删除一行后,使用SqlDataAdapter.Update(DataTable)无效,请教,下面贴出代码
/// <summary>
/// 将数据保存到数据库
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSave_Click(object sender, EventArgs e)
{
Save();
}
/// <summary>
/// 保存数据
/// </summary>
private void Save()
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlDataAdapter dap = CreateCustomerAdapter(connection);
DataTable dt = (DataTable)gvwEmp.DataSource;
dap.Update(dt);
}
}
/// <summary>
/// 构造SqlDataAdapter
/// </summary>
/// <param name="connection"></param>
/// <returns></returns>
public static SqlDataAdapter CreateCustomerAdapter(SqlConnection connection)
{
SqlDataAdapter dap = new SqlDataAdapter();
//Select
SqlCommand command = new SqlCommand("SELECT * FROM Customers", connection);
dap.SelectCommand = command;
//Insert
command = new SqlCommand("INSERT INTO Customers (序号,内容) VALUES (@序号, @内容)", connection);
command.Parameters.Add("@序号", SqlDbType.Int, 4, "序号");
command.Parameters.Add("@内容", SqlDbType.NVarChar, 300, "内容");
dap.InsertCommand = command;
//Update
command = new SqlCommand("UPDATE Customers SET 序号 = @序号, 内容 = @内容 WHERE ID = @ID", connection);
command.Parameters.Add("@序号", SqlDbType.Int, 4, "序号");
command.Parameters.Add("@内容", SqlDbType.NVarChar, 300, "内容");
SqlParameter parameter = command.Parameters.Add("@ID", SqlDbType.Int, 4, "ID");
parameter.SourceVersion = DataRowVersion.Original;
dap.UpdateCommand = command;
//Delete
command = new SqlCommand("DELETE FROM Customers WHERE ID = @ID", connection);
parameter = command.Parameters.Add("@ID", SqlDbType.Int, 4, "ID");
parameter.SourceVersion = DataRowVersion.Original;
dap.DeleteCommand = command;
return dap;
}