Home > Net >  How to resolve a null reference exception in vb.net
How to resolve a null reference exception in vb.net

Time:12-31

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim dt As New DataTable

        dt = CType(Session("buyitems"), DataTable)

        If (dt Is Nothing) Then
            Label5.Text = dt.Rows.Count.ToString()
        Else
            Label5.Text = "0"
        End If
    End Sub

    Protected Sub DataList1_ItemCommand(source As Object, e As DataListCommandEventArgs) Handles DataList1.ItemCommand

        Dim dlist As DropDownList = CType(e.Item.FindControl("DropDownList1"), DropDownList)
        Response.Redirect("AddToCart.aspx?id="   e.CommandArgument.ToString()   "&quantity="   dlist.SelectedItem.ToString)
    End Sub

I get the exception of System.NullreferenceException as "Object reference is not set to an instance of an object:

Exception Details

CodePudding user response:

If you have a DataTable stored in the Session variable buyitems then do not create a New one when you declare the local variable.

I think you just reversed assignments in the If statement.

It seems that there is not a DataTable in the Session variable.

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Dim dt As DataTable
    dt = CType(Session("buyitems"), DataTable)
    If dt Is Nothing Then
        Label5.Text = "0"
    Else
        Label5.Text = dt.Rows.Count.ToString()
    End If
End Sub

CodePudding user response:

If (dt Is Nothing) Then
        Label5.Text = "0"
    Else
        Label5.Text = dt.Rows.Count.ToString()
    End If

This code should solve the issue.

  • Related