在回发时以编程方式添加控件

时间:2009-11-19 12:45:13

标签: c# asp.net viewstate

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

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

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

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

在控件上启用ViewState没有用。如果只是那么简单:)

3 个答案:

答案 0 :(得分:5)

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

protected override void OnInit(EventArgs e)
{

    string dynamicControlId = "MyControl";

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

答案 1 :(得分:0)

CheckBox findme = PlaceHolder.FindControl("findme");

这是你的意思吗?

答案 2 :(得分:0)

您需要在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;
    }
}