【问题标题】:GridView row values not changed after updateGridView 行值在更新后未更改
【发布时间】:2013-04-22 05:50:43
【问题描述】:

我想用这段代码更新GridView 中的行,但在编辑GridView 后不会改变:

protected void res_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        //Retrieve the table from the session object.
        DataTable dt = (DataTable)Session["dt"];
        GridViewRow row =res.Rows[e.RowIndex];
        dt.Rows[row.DataItemIndex]["name"] = ((TextBox)(row.Cells[6].Controls[0])).Text;
        dt.Rows[row.DataItemIndex]["dewey"] = ((TextBox)(row.Cells[5].Controls[0])).Text;
        *dt.Rows[row.DataItemIndex]["subject"] = ((TextBox)(row.Cells[4].Controls[0])).Text;
        Session["dt"] = dt;
        res.EditIndex = -1;
        res.DataSource = dt;
        res.DataBind();
    }

我的Page_Load:

    protected void Page_Load(object sender, EventArgs e)
    {
        DataTable dt;
        if (!IsPostBack)
        {
            dt= Converter.ListBooks(new classes.Book().GetAll());
            Session["dt"] = dt;
            res.DataSource = dt;
            res.DataBind();
        }
        else
        {
            dt=(DataTable)Session["dt"];
            res.DataSource = dt;
            res.DataBind();
        }

    }

例如,我将带有 * 的行更改为:

dt.Rows[row.DataItemIndex]["subject"] = "tx";

并且编辑后的“主题”栏变成了“tx”,所以不知道为什么((TextBox)(row.Cells[4].Controls[0])).Text在编辑前返回TextBox的文字?

【问题讨论】:

  • 去掉page_load中的else部分,你真的不应该把它绑定在那里。请在引发回发的事件中绑定网格视图

标签: c# asp.net list gridview datatable


【解决方案1】:

因为您每次刷新页面(POST 或 GET)时都会调用 DataBind(); 方法,如果用户将新值放入 TextBox 并单击更新按钮触发,让我解释一下res_RowUpdating 甚至 Page_Load 都会触发并将 Gird 与旧值的数据库值绑定并忽略用户输入值。

【讨论】:

  • 我在 else 块中删除了 res.DataBind() 然后它起作用了。
【解决方案2】:

我想,你只需要重新绑定网格

【讨论】:

    【解决方案3】:

    删除page_load 中的else 部分。

    应该为你做。

    每次有postback 时,您都在绑定网格,这不是必需的。

    【讨论】:

      【解决方案4】:

      也许更改已完成,但表单未更新。

      尝试将 gridview 控件放在更新面板控件中并调用 UpdatePanel.Update()。

      当您使用 Web 控件时,您看到的可能与实际不同,因为数据的更改不会在表示层中自动更新。

      要解决这个“问题”,您可以对整个页面进行回发(检索所有内容),但这就像用火箭筒杀死苍蝇一样,因为您不需要所有内容,只需要已更新的内容,因此为此目的有几个工具可以让您进行部分更新,例如 AJAX 控件:UpdatePanel。

      希望对你有帮助。

      更新:调用 DataTable 上的 AcceptChanges() 方法,并在 if(!PostBack) 之后擦除 Page_Load 上的 else 分支

      【讨论】:

      • 这不是我的问题。我更改了不清楚的问题标题。
      • 所以您现在的问题不是应用更改,而是从您想要的某些行中获取文本?
      • 我的问题是((TextBox)(row.Cells[4].Controls[0])).Text 没有返回编辑值
      • 可能与您在网格内定义的控件有关,例如,如果您在尝试获取的列内定义了一个文本框,则访问该值的方式是:((TextBox )(row.Cells[4].Controls[0].Controls[0])).Text。您可以尝试使用 Visual Studio 找到正确的访问方式,在中间窗口中尝试粘贴我刚刚为您编写的代码。如果不起作用,请尝试复制gridview完整定义(aspx)
      【解决方案5】:

      调用DataTableAcceptChanges()方法,然后绑定GridView

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-12
        • 2020-07-18
        • 1970-01-01
        • 2018-11-29
        • 1970-01-01
        相关资源
        最近更新 更多