問題如標題所述。代碼如下:
頁面代碼
<asp:GridView ID="gdvCustomers" runat="server" Height="210px" OnRowEditing="gdvCustomers_RowEditing" Width="586px" OnRowDeleting="gdvCustomers_RowDeleting" OnRowUpdating="gdvCustomers_RowUpdating" OnRowCancelingEdit="gdvCustomers_RowCancelingEdit" AutoGenerateColumns="False" DataKeyNames="customerID"> <Columns> <asp:BoundField DataField="customerID" HeaderText="customerID"> </asp:BoundField> <asp:BoundField DataField="companyName" HeaderText="companyName"> </asp:BoundField> <asp:BoundField DataField="address" HeaderText="address"> </asp:BoundField> <asp:CommandField ShowEditButton="True" ShowDeleteButton="True" /> </Columns> </asp:GridView>
后台代碼
protected void gdvCustomers_RowUpdating(object sender, GridViewUpdateEventArgs e) { string id = ((TextBox)this.gdvCustomers.Rows[e.RowIndex].Cells[0].Controls[0]).Text.ToString(); string name = ((TextBox)this.gdvCustomers.Rows[e.RowIndex].Cells[1].Controls[0]).Text.ToString(); string address = ((TextBox)this.gdvCustomers.Rows[e.RowIndex].Cells[2].Controls[0]).Text.ToString(); string sql = "update customers set companyname='" + name + "',address='" + address + "' where customerid='" + id + "'"; SqlConnection con = new SqlConnection("Integrated Security=True;server=.;database=Northwind;"); SqlCommand cmd = new SqlCommand(sql, con); con.Open(); cmd.ExecuteNonQuery(); con.Close(); gdvCustomers.EditIndex = -1;//取消編輯狀態 DataLoad(); }
檢查GridView的gdvCustomers_RowUpdating事件,里面的代碼都是正確的,跟蹤sql語句發現,讀取的竟然不是修改后的值,而是原來的值。
最后發現,問題的關鍵,不在gdvCustomers_RowUpdating里面,而是Page_Load里面,沒有判斷是否是回傳,將GridView數據綁定的代碼放到IsPostBack判斷語句中,問題就解決了。代碼如下:
if (!this.IsPostBack) { DataLoad(); }
很久沒有弄WebForm了,竟然連這么基礎的知識都忘記!
