我在 Gridview 中使用 RowUpdating 事件。当我更新一行时,gridview 中的所有行都会更新。我的代码是
Con.Open();
SqlCommand cmd = new SqlCommand("update dbo.PersionalDetails set Name='" + txtName.Text + "',Location='" + txtLocation.Text + "' where id=id", Con);
cmd.ExecuteNonQuery();
Con.Close();
Label lblresult = new Label();
lblresult.ForeColor = Color.Green;
lblresult.Text = txtName.Text + " Details Updated successfully";
GridView1.EditIndex = -1;
BindGrid();
请帮忙!!
请您参考如下方法:
那是因为 where id = id 对所有行都是 true。它类似于 where 1 = 1 并且等于 where TRUE。这就是为什么您的所有行都更新了。
expression = expression
Return Types
Boolean
因为 id 是列名,所以它们是有效的 expressions .
我强烈觉得您想将此 id 添加为参数,但您甚至没有在代码中提及任何参数,所以..
也可以使用 using statement处理您的 SqlConnection 和 SqlCommand。
using (SqlConnection con = new SqlConnection(ConString))
{
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "update dbo.PersionalDetails set Name = @name, Location = @location where id = @id";
cmd.Parameters.AddWithValue("@name", txtName.Text);
cmd.Parameters.AddWithValue("@location", txtLocation.Text );
cmd.Parameters.AddWithValue("@id", YourIdValue);
con.Open();
cmd.ExecuteNonQuery();
}
}
但更重要
您应该始终使用 parameterized queries .这种字符串连接对于 SQL Injection 是开放的攻击。
因为我们不知道您的列类型,所以我在示例中使用了 AddWithValue 但没有使用此方法。使用 .Add()作为最佳实践。
