我有Gridview
完整的数据,我需要检查一些行时我可以按下按钮并相应地更改数据,我可以在检查所有行时执行此操作但我可以&#39 ;找到一种方法来连接我的查询与一行或多行的ID。
protected void UsedForButton_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
var chk = row.FindControl("InStockCbx") as CheckBox;
if (chk.Checked)
{
//using (WorkDBEntities db = new WorkDBEntities())
//{
// WorkTable table = new WorkTable();
// table.InStock = 0;
// db.WorkTables.Add(table);
// db.SaveChanges();
//}
string query = "UPDATE WorkTable SET InStock = 0 WHERE Id = " ???;
SqlCommand comm = new SqlCommand(query, conn);
conn.Open();
comm.ExecuteNonQuery();
conn.Close();
}
答案 0 :(得分:0)
@Nemanja,您希望获得每条记录的ID,然后只有您可以根据Id进行更新。首先将记录的Id绑定到网格中,并尝试在按钮单击事件中获取id
答案 1 :(得分:0)
试试这个:
protected void UsedForButton_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox checkbox1 = (CheckBox)row.FindControl("InStockCbx");
if (checkbox1.Checked)
{
int id = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Value.ToString());
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString);
SqlCommand cmd = new SqlCommand ("UPDATE WorkTable SET InStock = 0 WHERE Id = @Id"", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("@Id", SqlDbType.Int).Value = id;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
cmd.Dispose();
}
}
}
注意:您需要在.aspx
模板中指定数据密钥,如下所示:
<asp:GridView ID="GridView1" runat="server" DataKeyNames="id" ...>