Find control in class — cannot find control

旧时模样 提交于 2019-12-22 14:52:03

问题


I have an aspx page with an ajax tab container. In a class I want to find the tab container to pass some values.

I define myPage:

Page myPage = (Page)HttpContext.Current.Handler;

When looking in more details on this myPage by clicking add watch it is listing the tab container I am looking for. However when I define my tab container

AjaxControlToolkit.TabContainer Workflow_TabContainer = null;
Workflow_TabContainer = 
         (AjaxControlToolkit.TabContainer)myPage.FindControl("Workflow_TabContainer")
         as AjaxControlToolkit.TabContainer;

or

AjaxControlToolkit.TabContainer Workflow_TabContainer 
        (AjaxControlToolkit.TabContainer)myPage.FindControl("Workflow_TabContainer");

it does not find the tab container. I also tried to first define the page, than the ContentPlaceholder and searched for the tab container in the place holder. Same issue.

Any help and/or hint is much appreciated.

Thanks


回答1:


The FindControl method only looks in the current control for children.

If you don't know where in the page hierarchy the controls are, you'll need to do a recursive search - which is likely if you're using a templated control such as the TabContainer.

As I've posted previously to a similar answer:

private Control FindControlRecursive(Control rootControl, string controlID)
{
  if (rootControl.ID == controlID) {
    return rootControl;
  }

  foreach (Control controlToSearch in rootControl.Controls)
  {
    Control controlToReturn = 
      FindControlRecursive(controlToSearch, controlID);
    if (controlToReturn != null) { 
      return controlToReturn;
    }
  }

  return null;
}

Once you've got your control, you should cast it using as and then check for null just in case it's not quite what you were expecting:

var tabContainer = FindControlRecursively(myPage, "Workflow_TabContainer")
                 as AjaxControlToolkit.TabContainer

if (null != tabContainer) {
  // Do Stuff
}



回答2:


if the control is on the same page you can directly access the control. Have a look at the below:

http://www.dotnetcurry.com/ShowArticle.aspx?ID=178



来源:https://stackoverflow.com/questions/6572255/find-control-in-class-cannot-find-control

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