C# 访问在回发时以编程方式添加的控件

C# 访问在回发时以编程方式添加的控件,c#,asp.net,viewstate,C#,Asp.net,Viewstate,回发时:如何访问代码隐藏文件中以编程方式添加的ASP.NET控件 我正在向占位符控件添加复选框控件: PlaceHolder.Controls.Add(new CheckBox { ID = "findme" }); ASPX文件中添加的控件在Request.Form.AllKeys中显示良好,但我通过编程添加的控件除外。我做错了什么 在控件上启用ViewState没有帮助。要是这么简单就好了:) 这就是您的意思吗?您应该在回发时重新创建动态控件: protected override voi

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

我正在向占位符控件添加复选框控件:

PlaceHolder.Controls.Add(new CheckBox { ID = "findme" });
ASPX文件中添加的控件在
Request.Form.AllKeys
中显示良好,但我通过编程添加的控件除外。我做错了什么

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


这就是您的意思吗?

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

protected override void OnInit(EventArgs e)
{

    string dynamicControlId = "MyControl";

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

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

    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;
    }
找到扩展方法

公共静态类控制扩展
{
/// 
///递归查找指定父控件的子控件。
/// 
/// 
/// 
/// 
公共静态控件FindControlRecursive(此控件,字符串id)
{
if(control==null)返回null;
//尝试在当前级别查找控件
Control ctrl=Control.FindControl(id);
如果(ctrl==null)
{
//搜查孩子们
foreach(Control.Controls中的控件子级)
{
ctrl=FindControlRecursive(子级,id);
如果(ctrl!=null)中断;
}
}
返回ctrl;
}
}

是否在init事件中创建了动态控件?不完全是。我想在回发时访问控件。这不会重置控件的状态吗?如果在页面加载过程中在网页上勾选复选框(true),它将被读取为false,但是在按钮单击的事件处理程序中,它将具有正确的勾选值(true),这不会重置控件的状态吗?不,不会。要正确加载状态,每次重新创建时都需要相同的动态控件ID。
    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;
    }
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;
    }
}