用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