divya rao
divya rao

Reputation: 5

How to resolve a null reference exception in vb.net

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

Upvotes: 0

Views: 936

Answers (2)

Rakesh Androtula
Rakesh Androtula

Reputation: 403

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

This code should solve the issue.

Upvotes: 0

Mary
Mary

Reputation: 15101

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

Upvotes: 1

Related Questions