Find control in class — cannot find control

2019-05-23 07:04发布

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

2条回答
淡お忘
2楼-- · 2019-05-23 07:41

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
}
查看更多
干净又极端
3楼-- · 2019-05-23 07:57

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

查看更多
登录 后发表回答