title: Error 'Object reference not set to an instance of an object' during grid.FindControl
body: <p>Does anyone where is my code going wrong here? I have wrote the following code under .cs file to get the grid count:</p>
  
  <pre><code>    int totalCount = grid.FindControl("employee_to_rep").Controls.Count;
      for (int i = 0; i &lt; totalCount; i++)
      {
          CheckBox ck = (CheckBox)grid.FindControl("employee_to_rep").Controls[i];
          HiddenField employeeIDValue = (HiddenField)grid.FindControl("employeeidToRep").Controls[i];
          if (ck.Checked)
          {
              test = employeeIDValue.Value.ToString();
          }
      }
  </code></pre>
  
  <p>But error display when it come to the line (CheckBox)grid.FindControl("employee_to_rep").Controls[i];</p>
  
  <pre><code>Object reference not set to an instance of an object. 
  Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 
  
  Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
  
  Source Error: 
  
  Line 80: 
  Line 81:             int totalCount = grid.FindControl("employee_to_rep").Controls.Count;
  </code></pre>
  
  <p>Does anyone know what is it going on there?</p>
  
  <p>code in the aspx file:</p>
  
  <pre><code>    &lt;tr&gt;   
          &lt;th class="graytext r"&gt;Add Reps to Team:&lt;/th&gt;
          &lt;td&gt;               
           &lt;asp:GridView ID="grid" runat="server" AutoGenerateColumns="False" DataKeyNames="EmployeeID"
                  DataSourceID="dsEmployees" AllowPaging="true" PageSize="1000" EnableViewState="false"
                  GridLines="None" CssClass="clGridDirectory"&gt;
                  &lt;Columns&gt;
                    &lt;asp:TemplateField &gt;
                      &lt;ItemTemplate&gt;
                        &lt;asp:CheckBox runat="server" ID='employee_to_rep' Text='&lt;%# Eval("fullname") %&gt;'/&gt; 
                        &lt;asp:HiddenField runat="server" ID="employeeidToRep" Value='&lt;%# Eval("employeeid") %&gt;'/&gt;
                        &lt;asp:TextBox runat='server' ID='repID' Text='&lt;%# Eval("rep_id") %&gt;'/&gt;
                      &lt;/ItemTemplate&gt;
                    &lt;/asp:TemplateField&gt;
                  &lt;/Columns&gt;
                &lt;/asp:GridView&gt;       
             &lt;asp:SqlDataSource ID="dsEmployees" runat="server" ConnectionString="&lt;%$ ConnectionStrings:TestConnectionString %&gt;"
                  SelectCommand="app_staff_without_team_select" SelectCommandType="StoredProcedure"&gt;
            &lt;/asp:SqlDataSource&gt;          
          &lt;/td&gt;
      &lt;/tr&gt;  
  </code></pre>