[asp.net]GridView RowUpdating 不获取新数据

标签: Asp.net GridView C#
发布时间: 2016/11/13 8:38:52
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

当试图更新 GridView 数据,它成功地运行,但它获取的旧的数据,而不是您在文本框中键入数据。

这是我的有︰

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        string name = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text;
        string phone = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[2].Controls[0])).Text;
        string email = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text;
        int contactId = Convert.ToInt32(((TextBox)(GridView1.Rows[e.RowIndex].Cells[4].Controls[0])).Text);
        objLogic.UpdateContact(name, phone, email, contactId);  //passes values to SQL to update database
        GridView1.EditIndex = -1;
        GridView1.DataBind();
    }

    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        GridView1.DataBind();
    }

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DropDownList1.DataSource = objLogic.LoadClient();
            DropDownList1.DataTextField = "name";
            DropDownList1.DataValueField = "clientId";
            DropDownList1.DataBind();
        }

        GridView1.DataSource = objLogic.LoadContacts(Convert.ToInt16(DropDownList1.SelectedValue));
        GridView1.DataBind();

例如,当前的数据是︰

名称︰ 布雷克,电话︰ 123-234-3456,电子邮件︰ test@test.com,contactId: 22

键入新的数据︰

名称︰ 约翰,电话︰ 555-555-5555,电子邮件︰ test2@test2.com,contactId: 22

结束在数据库中的数据︰

名称︰ 布雷克,电话︰ 123-234-3456,电子邮件︰ test@test.com,contactId: 22

解决方法 1:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        DropDownList1.DataSource = objLogic.LoadClient();
        DropDownList1.DataTextField = "name";
        DropDownList1.DataValueField = "clientId";
        DropDownList1.DataBind();
        BindGrid();
    }
 }

protected void BindGrid()
{
    GridView1.DataSource = objLogic.LoadContacts(Convert.ToInt16(DropDownList1.SelectedValue));
    GridView1.DataBind();
}

每次回发的页绑定网格。将网格绑定移动到一个单独的函数。你行更新后,重新绑定网格。

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    string name = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text;
    string phone = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[2].Controls[0])).Text;
    string email = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text;
    int contactId = Convert.ToInt32(((TextBox)(GridView1.Rows[e.RowIndex].Cells[4].Controls[0])).Text);
    objLogic.UpdateContact(name, phone, email, contactId);  //passes values to SQL to update database
    GridView1.EditIndex = -1;
    BindGrid();
}

当您编辑时你必须太调用 BindGrid。

protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
    GridView1.EditIndex = e.NewEditIndex;
    //GridView1.DataBind(); this is meaningless, you have not set a DataSource
    BindGrid();
}
赞助商