asp.net 访问以编程方式在回发时添加的控件

ioekq8ef  于 2023-02-14  发布在  .NET
关注(0)|答案(3)|浏览(124)

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

我正在将CheckBox控件添加到Placeholder控件:

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

ASPX文件中添加的控件在Request.Form.AllKeys中显示良好,除了我以编程方式添加的控件。我做错了什么?
在控件上启用ViewState没有帮助。如果真的这么简单就好了:)

wqsoz72f

wqsoz72f1#

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

protected override void OnInit(EventArgs e)
{

    string dynamicControlId = "MyControl";

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

svgewumm2#

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

你是这个意思吗?

chy5wohz

chy5wohz3#

您需要在Page_Load期间添加动态添加控件,以便每次都正确地构建页面,然后在您的(我假设单击按钮)中,您可以使用扩展方法(如果您使用Python 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;
    }
}

相关问题