我在执行多个 sqlcommands 时遇到问题。我需要多次更新数据。第一个 sql 查询针对两种情况 if,else; 但是第二个和第三个 sqlcommand 将在 if 或 else 中。问题是只有一个 sqlcommand 可以正常工作,那些位于循环内的。
public void Button_Submit_Onclick(object sender, EventArgs e)
{
for (int i = 0; i < GridView2.Rows.Count; i++)
{
con.ConnectionString = ConfigurationManager.ConnectionStrings["TestDeductionsConnectionString2"].ToString();
int recordid = Convert.ToInt32(GridView2.DataKeys[i].Values[0]);
CheckBox cbox = (CheckBox)GridView2.Rows[i].FindControl("CheckBox1");
bool private1 = Convert.ToBoolean(cbox.Checked);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "Update DetailCosts set private='" + private1 + "' where recordid=" + recordid;
con.Open();
if (private1==true)
{
cmd.CommandText = "Update DetailCosts set privateCost=Costs where recordid=" + recordid;
cmd.Parameters.AddWithValue("@private1", SqlDbType.Bit).Value = private1;
cmd.Parameters.AddWithValue("@recordid", SqlDbType.Int).Value = recordid.ToString();
}
else
{
cmd.CommandText = "Update DetailCosts set privateCost=0 where recordid=" + recordid;
cmd.Parameters.AddWithValue("@recordid", SqlDbType.Int).Value = recordid.ToString();
cmd.Parameters.Add("@private1", SqlDbType.Bit).Value = private1;
}
cmd.ExecuteNonQuery();
con.Close();
}
}
相关分类