0

GridView1我正在尝试从这里切换我在gridview上的代码:

        <asp:SqlDataSource ID="dsPar" runat="server" ConnectionString="<%$ ConnectionStrings:connstring %>"
        SelectCommand="SELECT ID,  FileNumber, address, phone from myTable ORDER BY ID"  FilterExpression="ID like '%{0}%'">
        <FilterParameters>
        <asp:ControlParameter Name="StreetSrch" ControlID="searchBox" PropertyName="Text" />
        </FilterParameters>
        </asp:SqlDataSource>

对此:

    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

最后,下面是标记的快照:

<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">

我正在"Object reference not set to an instance of an object."以下行:

第 44 行:Dim chkAll As CheckBox = DirectCast(GridView1.HeaderRow.Cells(0).FindControl("chkAll"), CheckBox)

知道如何解决这个问题吗?

代码很长,我不想在这里全部发布。如果需要,我可以发布更多。

4

4 回答 4

0

尝试调暗作为对象的新实例,这可能会导致您的问题?当我得到这个特殊的异常时,通常是因为我在没有“新”的情况下暗淡了一些东西

希望这可以帮助!

于 2012-08-30T14:59:37.443 回答
0

您可以使用断点和监视窗口来找出您的代码到底哪里出错了。每当您尝试对NullReferenceException变量调用方法时都会抛出Nothing.

Option Infer On 的代码示例:

Dim firstHeaderCell = GridView1.HeaderRow.Cells(0)
Debug.Assert(firstHeaderCell IsNot Nothing, "Couldn't find the first header cell")
Dim chkAllControl = firstHeaderCell.FindControl("chkAll")
Debug.Assert(chkAllControl IsNot Nothing, "Couldn't find a control named chkAll")
Dim chkAll As CheckBox = TryCast(chkAllControl, CheckBox)
Debug.Assert(chkAll IsNot Nothing, "chkAll exists but it isn't a CheckBox")

这些断言完全是矫枉过正,但不能给出带有“断点”和“观察窗口”变量的代码示例。

于 2012-08-30T15:04:52.223 回答
0

IT 抛出空引用异常,因为

GridView1.HeaderRow.Cells(0).FindControl("chkAll")

没有找到一个复选框,所以它返回 null (Nothing) 所以你实际上正在做的就是试图将 Nothing 转换为一个复选框。

于 2012-08-30T15:05:58.430 回答
0

中断该行的调试器。然后,您可以使用“快速查看”功能查看该行的某些部分以查看哪些内容为空。首先查看 GridView1。如果不为空,请查看 GridView1.HeaderRow。继续,直到找到空对象。

于 2012-08-30T15:01:45.620 回答