title: Why am I getting "Object reference not set to an instance of an object." error?
body: <p>GridView1I am trying to switch my code on gridview from this:</p>
  
  <pre><code>        &lt;asp:SqlDataSource ID="dsPar" runat="server" ConnectionString="&lt;%$ ConnectionStrings:connstring %&gt;"
          SelectCommand="SELECT ID,  FileNumber, address, phone from myTable ORDER BY ID"  FilterExpression="ID like '%{0}%'"&gt;
          &lt;FilterParameters&gt;
          &lt;asp:ControlParameter Name="StreetSrch" ControlID="searchBox" PropertyName="Text" /&gt;
          &lt;/FilterParameters&gt;
          &lt;/asp:SqlDataSource&gt;
  </code></pre>
  
  <p>to this:</p>
  
  <pre><code>    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
          Dim strQuery As String = "SELECT ID,  FileNumber, address, Phone from MyTable WHERE Id LIKE '%@strSearch%'  ORDER BY Id"
  
          Dim cmd As New SqlCommand(strQuery)
          Dim dt As DataTable = GetData(cmd)
          Dim CheckBoxArray As ArrayList
          If ViewState("CheckBoxArray") IsNot Nothing Then
              CheckBoxArray = DirectCast(ViewState("CheckBoxArray"), ArrayList)
          Else
              CheckBoxArray = New ArrayList()
          End If
  
          If Not IsPostBack Then
              Gridview1.DataBind()
              Dim CheckBoxIndex As Integer
              Dim CheckAllWasChecked As Boolean = False
              Dim chkAll As CheckBox = DirectCast(GridView1.HeaderRow.Cells(0).FindControl("chkAll"), CheckBox)
  rest of code....
  End If
  End Sub
  </code></pre>
  
  <p>Finally, below is a snapshot of the markup:</p>
  
  <pre><code>&lt;asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" AllowPaging="True"
                  OnPageIndexChanging = "OnPaging" HeaderStyle-CssClass = "header" Font-Size = "10pt" 
                   AlternatingRowStyle-BackColor = "#C2D69B" OnRowDataBound = "RowDataBound" AllowSorting="true" 
                   PageSize="20" CssClass="Gridview" 
                   GridLines="None"&gt;
  </code></pre>
  
  <p>I am getting <code>"Object reference not set to an instance of an object."</code> on the following line:</p>
  
  <p>Line 44:             Dim chkAll As CheckBox = DirectCast(GridView1.HeaderRow.Cells(0).FindControl("chkAll"), CheckBox)</p>
  
  <p>Any idea how to resolve this?</p>
  
  <p>Code is very long and I didn't want to post all of it here. I can post more if needed.</p>