用GridView自帶的更新功能,數據不更新的問題


    問題如標題所述。代碼如下:   

頁面代碼
<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了,竟然連這么基礎的知識都忘記!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM