NullException错误

时间:2014-11-17 04:54:43

标签: vb.net

我在浏览网页时遇到了一些麻烦。我一直得到NullException Error并且不知道如何让我的代码能够运行。这是我目前的代码。

Imports System.Data
Imports System.Data.SqlClient

Partial Class Proj_product
    Inherits System.Web.UI.Page   

    Private Sub ProductDisplayValues(ByVal temp As String)
        Dim SearchId As Int32 = Convert.ToInt32(temp) 'Searching for a product with this ID
        Session("ProductPicID") = SearchId 'Record SearchID as a session variable
        Dim myGlobal As New clsGlobal

        'declare and open a connection to the Catalog table. 
        'Select the product with ID number equal to SearchID
        Dim cnnSQL As New SqlConnection(myGlobal.cnnstring)
        Dim cmd As New SqlCommand("Select PROD_NAME, PROD_PRICE, PROD_DESC from CATALOG Where PROD_ID = " & SearchId, cnnSQL)

        Dim rdr As SqlDataReader
        Try
            cnnSQL.Open()
            rdr = cmd.ExecuteReader()
            If rdr.Read Then
                lblName.Text = rdr(0) 'Read Name
                lblPrice.Text = rdr(1) 'Read Price
                'Change price format to 2 decimal places
                lblPrice.Text = "$" & Mid(lblPrice.Text, 1, Len(lblPrice.Text) - 2)
                txtDescription.Text = rdr(2) 'Read Description
            End If
            rdr.Close()
            cnnSQL.Close()
        Catch ex As Exception
            Response.Write(ex.Message)
        End Try
    End Sub
    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim CaptureId() As String

        'ValueID is a collection of parameters passed from the catalog page
        'by the Java code and the click event that we wrote for thumbnails
        'In our case there is just one parameter: ID
        Dim ValueID As System.Collections.Specialized.NameValueCollection
        ValueID = Request.QueryString
        'Retrieve parameter value from the collection and assign it to CaptureID
        CaptureId = ValueID.GetValues("Id")
        'Call procedure that displays product information
        Call ProductDisplayValues(CaptureId(0).ToString)     "Here is where the NullException Occurs"
    End Sub    

    Private Sub btnReturnCatalog_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnReturnCatalog.Click
        Response.Redirect("catalog.aspx")
    End Sub

End Class

2 个答案:

答案 0 :(得分:0)

如果CaptureId(0)为空,则在其上调用ToString将导致异常。在调用之前检查值是否为空。

BTW,CaptureId中的元素无论如何都是String,因此您可以一起省略方法调用。

答案 1 :(得分:-2)

在使用CaptureId(0)之前,您可以检查CaptureId的长度,该长度必须大于0.