I have a TextBox with id=txtPlace and a gridview. If a user selects a row an put some Information in the TextBox and click on save. The Information should replace older records in the database(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); } }
But It does not work. When I click on save, nothing happens.
You're missing a couple crucial steps - opening the SqlConnection
and executing the SqlCommand
. Since this is something where you don't expect a result back, you can just use ExecuteNonQuery()
. You probably should wrap SqlCommand
in a using
block as well, since it's IDisposable
, and your variable is incorrectly named.
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
}
}
}
string query = "UPDATE user SET place= @place where ID = @D ";
我猜您输入了错误的变量名,看起来@D与@ID不同
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.