【问题标题】:Recursively traversing controls In OnInit disables GridView RowCommand and loses Viewstate在 OnInit 中递归遍历控件会禁用 GridView RowCommand 并丢失 Viewstate
【发布时间】:2013-03-14 16:04:08
【问题描述】:

如果我递归地遍历页面的控件,则 RowCommand 事件不再由 GridView 中的 LinkBut​​tons 触发。事实上,看起来 GridView 的 ViewState 丢失了。为什么?我该如何解决这个问题?

在您取消注释 //recurse(this.Controls) 行之前,以下代码将正常工作。然后,当您点击链接时,GridView 消失并且 RowCommand 永远不会被触发。

我的页面的完整<body>

<form id="form1" runat="server">
    <asp:GridView ID="gv" AutoGenerateColumns="False" runat="server" onrowcommand="gv_RowCommand">
        <Columns><asp:TemplateField HeaderText="Link"><ItemTemplate>
            <asp:LinkButton ID="lnk" runat="server" CommandArgument = 'xxx'>xxx</asp:LinkButton>
        </ItemTemplate></asp:TemplateField></Columns>
    </asp:GridView>
</form>

我的代码:

    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        //recurse(this.Controls);
    }
    private static void recurse(ControlCollection controls)
    {
        foreach (Control control in controls)
            recurse(control.Controls);
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            var dt = new DataTable();
            dt.Columns.Add("Link", typeof(string));
            DataRow dr = dt.NewRow();
            dr["Link"] = "google.com";
            dt.Rows.Add(dt);
            DataSet ds = new DataSet();
            ds.Tables.Add(dt);
            gv.DataSource = ds;
            gv.DataBind();
        }
    }
    protected void gv_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (this.Application["counter"] == null)
            this.Application["counter"] = 0;
        this.Application["counter"] = (int)this.Application["counter"] + 1;
        Response.Write("JUNK" + this.Application["counter"]);
    }

【问题讨论】:

  • 你想用recurse完成什么?
  • 在我的真实代码中,我正在按名称搜索一些控件,以便可以适当地设置它们的属性。 OnInit 中的代码正在清除它们。稍后也可以访问它们(在 Page_Load 等中),但那些递归搜索工作正常。
  • 你在哪里设置这些控件的属性?如果我们知道您想要达到的目标,您可以为您提供替代解决方案。
  • @Magnus 你不需要真正的递归函数来解释为什么这会导致问题。问题出在我给出的代码中。如果我知道原因,我可能会自己想出一个合理的解决方法。
  • 看来你不是唯一一个有这个问题的人,见forums.asp.net/t/1043999.aspx/1

标签: c# asp.net webforms


【解决方案1】:

@jbl 找到了一些对我来说足够好的解释(感谢搜索技巧!)。这个问题之前在这里看到过:http://forums.asp.net/t/1043999.aspx/1

总结该页面,在 Init 阶段以任何方式访问 GridView 的 .Controls 属性都会破坏其 ViewState。没有解释为什么,但无论如何已经观察到了。

该页面上有一个对我来说足够好的解决方法。如果您检查每个控件以查看其是否为.HasControls(),如果没有则不访问其.Controls 属性,ViewState 不会丢失,因此事件将正常触发。

附:我猜这是一个错误,但由于向后兼容性,它当然不能永远更改:(

【讨论】:

    猜你喜欢
    • 2015-04-01
    • 2016-08-25
    • 2014-10-25
    • 2021-04-15
    • 1970-01-01
    • 2016-03-12
    • 2018-07-12
    • 2014-03-11
    • 1970-01-01
    相关资源
    最近更新 更多