Cannot Access the Controls inside an UpdatePanel

女生的网名这么多〃 提交于 2020-01-07 07:48:40

问题


What I am trying to do is accessing Page Controls at Page_Load, and make a database query, and make controls visible or not visible.

Here is the Code:

foreach (Control thiscontrol in ContentPlaceHolderBody.Controls) {
    try {
        if (thiscontrol.ID.Contains("TextBox") || thiscontrol.ID.Contains("Label")) {
            string dummy = thiscontrol.ID;
            bool IsValid = db.Roles.Any(a => a.controlName == dummy);
            if (IsValid == false)
                thiscontrol.Visible = false;
        }
        else if (thiscontrol.ID.Contains("UpdatePanel")) {
            foreach (Control UPcontrols in ((UpdatePanel)thiscontrol).ContentTemplateContainer.Controls) {
                if (UPcontrols.ID.Contains("TextBox") || UPcontrols.ID.Contains("DropDownList")) {
                    bool UPIsValid = db.Roles.Any(a => a.controlName == UPcontrols.ID);
                    if (UPIsValid == false)
                        UPcontrols.Visible = false;
                }
            }
        }
    }
    catch { }
}

My Problem is with the UPcontrols! It should retrieve the controls within the UpdatePanel, but the thing is it doesn't do its job, except in the debug mode!

When I add a breakpoint, everything is OK, but when I run the web application, it doesn't find any components within the UpdatePanel...


回答1:


Try this one:

ControlCollection cbb = updatepanel1.Controls;
ControlCollection cb = cbb[0].Controls;

initialize_Controls(cb);

public void initialize_Controls(ControlCollection objcontrls)
{

    foreach (Control tb in objcontrls) {
        if (tb is TextBox)
            ((TextBox)tb).Text = "";


        if (tb is Panel) {
            ControlCollection cbcll = tb.Controls;

            foreach (Control tbb in cbcll) {
                if (tbb is TextBox)
                    ((TextBox)tbb).Text = "";
            }
        }
    }
}

First find controls from updatepanel i.e ContentTemplate, then find controls from contentTemplate which contain all controls in it.




回答2:


This seems like a very bizarre design. That is, using control IDs for such purposes is rather unusual.

Nevertheless, you need a recursive method here to do a deep walk of every control on the page. Your method will not work if the UpdatePanel is contained within another control.




回答3:


Have a check on this article

http://www.codeproject.com/Articles/24178/The-magical-effects-of-the-UpdatePanel-control-in



来源:https://stackoverflow.com/questions/1954366/cannot-access-the-controls-inside-an-updatepanel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!