通过单击按钮更新gridview中的全部内容

时间:2015-09-14 08:05:21

标签: c# asp.net

我需要通过单击按钮更新我的整个gridview详细信息。现在我有一个编码。但是我编辑网格视图并单击更新按钮,然后第一行只更新,keepins不更新。请帮助。这是我的代码。

protected void Button8_Click(object sender, EventArgs e)
    {
        int RowIndex = 0;
        {
                GridViewRow row = (GridViewRow)GridView1.Rows[RowIndex];
                TextBox txtcode = row.FindControl("txtcode") as TextBox;
                TextBox txtalt = row.FindControl("txtalt") as TextBox;
                TextBox txtdetail = row.FindControl("txtdetails") as TextBox;
                SqlConnection myConnection = new SqlConnection("Data Source=SOMATCOSVR2015;
                                 Initial Catalog=SimsVisnu;User ID=sa;Password=aDmin123");
                SqlCommand cmd = new SqlCommand("UPDATE Qtattemp SET Code = @Code, 
                                    details = @details WHERE Code = @Code", myConnection);
                cmd.Parameters.AddWithValue("@Code", txtcode.Text.Trim());
                cmd.Parameters.AddWithValue("@details", txtdetail.Text.Trim());
                myConnection.Open();
                cmd.ExecuteNonQuery();
                GridView1.EditIndex = -1;
                DataBind();
                Response.Redirect(Request.Url.AbsoluteUri);
        }
    } 

1 个答案:

答案 0 :(得分:1)

因为您只是指定第一行的索引。你需要像这样遍历每一行: -

int totalRows = GridView1.Rows.Count;
for (int RowIndex = 0; i < totalRows; RowIndex++)
    {
        GridViewRow row = GridView1.Rows[RowIndex];
        TextBox txtcode = row.FindControl("txtcode") as TextBox;
        TextBox txtalt = row.FindControl("txtalt") as TextBox;
        TextBox txtdetail = row.FindControl("txtdetails") as TextBox;
        SqlConnection myConnection = new SqlConnection("Data Source=SOMATCOSVR2015;
                                Initial Catalog=SimsVisnu;User ID=sa;Password=aDmin123");
        SqlCommand cmd = new SqlCommand("UPDATE Qtattemp SET Code = @Code,
                                   details = @details WHERE Code = @Code", myConnection);
        cmd.Parameters.AddWithValue("@Code", txtcode.Text.Trim());
        cmd.Parameters.AddWithValue("@details", txtdetail.Text.Trim());
        myConnection.Open();
        cmd.ExecuteNonQuery();
     }
 Response.Redirect(Request.Url.AbsoluteUri);

另外,我建议创建一个单独的图层来处理数据库操作。在执行SQL相关查询时,请考虑使用using statement。另请阅读Can we stop using AddWithValue

<强>更新

旁注:

1)将您的gridview绑定在!IsPostBack内 2)不要在环路内部或外部再次绑定网格视图 3)我没有找到任何使用GridView1.EditIndex更新EditIndex的理由。不要更新它。