我有一个带有id = txtPlace和gridview的TextBox。如果用户选择一行,则在TextBox中放入一些信息,然后单击“保存”。信息应该替换数据库中的旧记录(SQL)
protected void btnSave_Click(object sender, EventArgs e)
{
var id = GridView2.SelectedDataKey.Values[0].ToString();
string constr = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
using (SqlConnection conn = new SqlConnection(constr))
{
string query = "UPDATE user SET place= @place where ID = @ID ";
SqlCommand cmd = new SqlCommand(query, conn);
cmd.Parameters.AddWithValue("@place", txtPlace.Text);
cmd.Parameters.AddWithValue("@ID", id);
}
}
但它不起作用。当我点击保存时,没有任何反应。
答案 0 :(得分:2)
您错过了几个关键步骤 - 打开SqlConnection
并执行SqlCommand
。由于这是您不希望返回结果的内容,因此您可以使用ExecuteNonQuery()
。您可能也应该将SqlCommand
包裹在using
块中,因为它是IDisposable
,并且您的变量命名不正确。
protected void btnSave_Click(object sender, EventArgs e)
{
var id = GridView2.SelectedDataKey.Values[0].ToString();
string constr = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
using (SqlConnection conn = new SqlConnection(constr))
{
conn.Open(); // actually connect to the server
string query = "UPDATE user SET place= @place where ID = @ID "; // change @D to @ID
using (SqlCommand cmd = new SqlCommand(query, conn))
{
cmd.Parameters.AddWithValue("@place", txtPlace.Text);
cmd.Parameters.AddWithValue("@ID", id);
cmd.ExecuteNonQuery(); // actually execute your statement
}
}
}
答案 1 :(得分:0)
string query = "UPDATE user SET place= @place where ID = @D ";
我猜你输了错误的变量名,看看@D与@ID不同