Using FindControl to get GridView in a Content Page

gcoleman0828 picture gcoleman0828 · Jun 29, 2011 · Viewed 16.1k times · Source

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 keep getting Object reference not set to an instance of an object. I'm sure there is a simple step I'm missing, but in my research I cannot seem to find anything.

Aspx code

  <asp:GridView ID="GridView1" EnableViewState="true" 
    runat="server"  
    BackColor="White" BorderColor="#CC9966"
    BorderStyle="None" BorderWidth="1px" CellPadding="4" Width="933px" 
    onrowdatabound="GridView1_RowDataBound"  
    onrowdeleting="GridView1_RowDeleting" 
    onrowediting="GridView1_RowEditing"
    onrowupdating="GridView1_RowUpdating" 
    onsorting="GridView1_Sorting"
    AllowSorting="true"
    AutoGenerateColumns="False" 
    PersistedSelection="true" onrowcancelingedit="GridView1_RowCancelingEdit">
    <EditRowStyle Font-Size="Small" Width="100px" />
    <FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
    <Columns>
      <asp:TemplateField>
        <ItemTemplate>
          <asp:LinkButton runat="server" ID="EditLinkButton" CausesValidation="True"
                          Text="Edit" CommandName="Edit"/>
          <asp:LinkButton runat="server" ID="DeleteLinkButton" CausesValidation="False"
                          Text="Delete" CommandName="Delete"/>
        </ItemTemplate>
        <EditItemTemplate>
          <asp:LinkButton runat="server" ID="UpdateLinkButton" CausesValidation="True"
                          Text="Update" CommandName="Update"/>
          <asp:LinkButton runat="server" ID="CancelLinkButton" CausesValidation="False"
                          Text="Cancel" CommandName="Cancel"/>
        </EditItemTemplate>
      </asp:TemplateField>
    </Columns>
  </asp:GridView>

.cs code

protected void Page_Load(object sender, EventArgs e) {
  SetDirectory();

  System.Web.UI.Page page = (System.Web.UI.Page)System.Web.HttpContext.Current.Handler;
  GridView GridViewCopy = (GridView)page.FindControl("GridView1");

  Log.WriteLine("SortBindGrid: GridView Row Count: " + 
                GridViewCopy.Rows.Count, Log.DEBUG_LEVEL.TERSE);
  return;
}

I've tried a few variations of using MainContent_GridView for the find to get and Master.FindControl with all the same result.

Answer

Zhaph - Ben Duguid picture Zhaph - Ben Duguid · Jun 30, 2011

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
}