如何在网格视图中编辑和更新行值?

我有这样的网格视图:

        <asp:Label ID="lblProdID" runat="server" Text=''>   <asp:TextBox ID="txtProdID" runat="server" Text=''>        <asp:Label ID="lblProdName" runat="server" Text=''>   <asp:TextBox ID="txtProdName" runat="server" Text=''>          

这是页面背后的代码

  protected void gvProducts_RowEditing(object sender, GridViewEditEventArgs e) { gvProducts.EditIndex = e.NewEditIndex; } protected void gvProducts_RowUpdating(object sender, GridViewUpdateEventArgs e) { int i = e.RowIndex; object control = gvProducts.Rows[i].FindControl("txtProdID"); //i want to access the new value from the object "control" but im getting the previous value only } 

试试这个

 protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) { TextBox txtProdID = (TextBox)gvProducts.Rows[e.RowIndex].FindControl("txtProdID"); TextBox txtProdName = (TextBox)gvProducts.Rows[e.RowIndex].FindControl("txtProdName"); //Call update method Product.Update(txtProdId,txtProdName); gvProducts.EditIndex = -1; //Refresh the gridviwe BindGrid(); } 

您需要检查e.NewValues字典以获取更新的数据。

我在下面有一个示例,GridView模板绑定到CategoryName。 单击“编辑”按钮时会触发OnRowUpdating。 在RowUpdating事件处理程序中,它获取文本框绑定到的CategoryName数据。

注意:在正常模式下使用标签不是使用TextBox。

              

后台代码:

 public void HandleOnGridViewRowUpdating(object sender, GridViewUpdateEventArgs e) { if (e.NewValues["CategoryName"] != null) { String newCategoryName = e.NewValues["CategoryName"].ToString(); // process the data; } }