简体   繁体   English

如何在Gridview中更新选定的行?

[英]How to update selected row in Gridview?

I have a TextBox with id=txtPlace and a gridview. 我有一个id = txtPlace和gridview的TextBox。 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) 该信息应替换数据库中的旧记录(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 . 您缺少几个关键步骤-打开SqlConnection并执行SqlCommand Since this is something where you don't expect a result back, you can just use ExecuteNonQuery() . 由于这是您不希望返回结果的地方,因此可以只使用ExecuteNonQuery() You probably should wrap SqlCommand in a using block as well, since it's IDisposable , and your variable is incorrectly named. 您可能还应该将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
        }
    }
}
string query = "UPDATE user SET place= @place where ID = @D ";

我猜您输入了错误的变量名,看起来@D与@ID不同

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM