【问题标题】:Accessing controls added programmatically on postback访问回发时以编程方式添加的控件
【发布时间】:2009-11-19 22:06:49
【问题描述】:

回发时:如何访问以编程方式添加的代码隐藏文件中的 ASP.NET 控件?

我正在向占位符控件添加 CheckBox 控件:

PlaceHolder.Controls.Add(new CheckBox { ID = "findme" });

在 ASPX 文件中添加的控件在 Request.Form.AllKeys 中显示良好,但我以编程方式添加的控件除外。我做错了什么?

在控件上启用 ViewState 没有帮助。要是这么简单就好了:)

【问题讨论】:

  • 你在init事件中创建了动态控制吗?

标签: c# asp.net viewstate


【解决方案1】:

您应该在回发时重新创建动态控件:

protected override void OnInit(EventArgs e)
{

    string dynamicControlId = "MyControl";

    TextBox textBox = new TextBox {ID = dynamicControlId};
    placeHolder.Controls.Add(textBox);
}

【讨论】:

  • 这不会重置控件的状态吗?
  • 不,不会。要正确加载状态,需要相同的动态控件 ID - 每次重新创建它。
【解决方案2】:
CheckBox findme = PlaceHolder.FindControl("findme");

你是这个意思吗?

【讨论】:

  • 不完全是。我想访问回发控件。
【解决方案3】:

您需要在 Page_Load 期间添加动态添加控件以每次正确构建页面。然后在您的(我假设单击按钮)中,您可以使用扩展方法(如果您使用的是 3.5)找到您在 Page_Load 中添加的动态控件

    protected void Page_Load(object sender, EventArgs e)
    {
        PlaceHolder.Controls.Add(new CheckBox {ID = "findme"});
    }

    protected void Submit_OnClick(object sender, EventArgs e)
    {
        var checkBox = PlaceHolder.FindControlRecursive("findme") as CheckBox;
    }

找到扩展方法here

public static class ControlExtensions
{
    /// <summary>
    /// recursively finds a child control of the specified parent.
    /// </summary>
    /// <param name="control"></param>
    /// <param name="id"></param>
    /// <returns></returns>
    public static Control FindControlRecursive(this Control control, string id)
    {
        if (control == null) return null;
        //try to find the control at the current level
        Control ctrl = control.FindControl(id);

        if (ctrl == null)
        {
            //search the children
            foreach (Control child in control.Controls)
            {
                ctrl = FindControlRecursive(child, id);
                if (ctrl != null) break;
            }
        }
        return ctrl;
    }
}

【讨论】:

  • 这不会重置控件的状态吗?
  • 如果在 Page_Load 期间在网页上勾选了复选框(true),它将被读取为 false,但是在 Button Click 的事件处理程序中,它将具有正确的勾选值(true)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多