Using FindControl to get GridView in a Content Page

被刻印的时光 ゝ 提交于 2019-11-29 16:27:44

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
}

Don't get the page from HttpContext if you are already within the page. Instead, is there a control you can use FindControl from? Instead of use page, use:

parentControl.FindControl("GridView1") as GridView;

Instead. There is an issue with finding the grid from the page level, and using a lower level control closer to the grid will have better success.

Brian got it right but he forgot the essential part. You won't be able to do use his code unless you add this code on top of your HTML-Code of the file where you want to use it.(Page.aspx)

<%@ MasterType VirtualPath="~/Master/Site.master" %>

then you can use the code Brian suggested:

GridView grid = this.Master.FindControl("GridView1");

Edit: If you want to use the gridview from within another class in the same file i would use the following: Add this to the class created when you make the page

 public partial class YourPageName: System.Web.UI.Page
 {
    public static Gridview mygrid = this.GridviewnameOFYourASPX
    ...
 }

And to your custom class add this in your method

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