Using FindControl to get GridView in a Content Page

前端 未结 3 1621
忘掉有多难
忘掉有多难 2020-12-21 14:32

I would like to find a GridView Control within a separate class and I am having issues doing so. I even tried placing my code in the aspx.cs page to no avail. I

3条回答
  •  南笙
    南笙 (楼主)
    2020-12-21 15:21

    In one of your comments you state that the GridView isn't on the Master Page, so is it safe to assume that it's on a page that uses a Master Page? And therefore it must be in a ContentPlaceholder control?

    The key issue is that FindControl method only looks for direct children (emphasis added):

    This method will find a control only if the control is directly contained by the specified container; that is, the method does not search throughout a hierarchy of controls within controls.

    So you either need to:

    1. Search for the control within the correct ContentPlaceholder control, rather than from Page.
    2. Loop through each of the Controls in Page.Controls recursively until you find the control you're after.

    An example of 2:

    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 gridView = FindControlRecursively(Page, "GridView1") as GridView
    
    if (null != gridView) {
      // Do Stuff
    }
    

提交回复
热议问题