NullReferenceException - 未将对象引用设置为对象的实例

时间:2013-04-08 13:25:54

标签: asp.net vb.net sql-server-2012

我正在尝试运行以下代码。它以前工作,但当我添加第二个datareader时,它停止了。谁能告诉我什么是错的?

Protected Sub btnSearchUser_Click(sender As Object, e As EventArgs) Handles btnSearchUser.Click

        Dim conn As New SqlConnection("Data Source=BRIAN-PC\SQLEXPRESS;Initial Catalog=master_db;Integrated Security=True")
        Dim searchComm As String = "SELECT * FROM users WHERE username LIKE @username"
        Dim user_id_select As New Integer

        Dim searchSQL As New SqlCommand

        conn.Open()

        searchSQL = New SqlCommand(searchComm, conn)
        searchSQL.Parameters.AddWithValue("@username", txtUserSearch.Text)

        Dim datareader As SqlDataReader = searchSQL.ExecuteReader()

        While datareader.Read

            lstUsers.Items.Add(datareader.Item("username"))

        End While

        datareader.Close()
        conn.Close()


        Dim conn2 As New SqlConnection("Data Source=BRIAN-PC\SQLEXPRESS;Initial Catalog=master_db;Integrated Security=True")
        Dim selectComm As String = "SELECT user_id FROM users WHERE username=@username_selected"

        Dim selectSQL As New SqlCommand

        conn2.Open()


        selectSQL = New SqlCommand(selectComm, conn2)
        selectSQL.Parameters.AddWithValue("@username_selected", lstUsers.SelectedItem.Text.Trim)

        Dim datareader2 As SqlDataReader = selectSQL.ExecuteReader()

        While datareader2.Read

            If datareader2.HasRows Then

                user_id_select = datareader2("user_id")

                lblUserSelected.Text = "Selected: " + lstUsers.SelectedItem.Text

            ElseIf datareader2.HasRows = False Then

                lblInvalidUsername.Visible = True
                datareader2.Close()


            End If

        End While


        conn2.Close()



    End Sub

enter image description here

您好,

每当我在lblUserSelected.Text = "Selected: " + lstUsers.SelectedItem.Text输入用户名并点击搜索时,我就会在txtUserSearch上获得NullReference异常,之前它正在运行..我不知道发生了什么..

谁能告诉我什么错了?

1 个答案:

答案 0 :(得分:0)

我假设你在这一行得到了NullReferenceException

selectSQL.Parameters.AddWithValue("@username_selected", lstUsers.SelectedItem.Text.Trim)

因为您尚未指定最近填充的SelectedItem的{​​{1}}。要选择第一个项目,您可以使用此代码:

ListBox

您也没有处理数据库中没有用户名的情况,While datareader.Read lstUsers.Items.Add(datareader.Item("username")) End While If lstUsers.Items.Count <> 0 Then lstUsers.SelectedIndex = 0 为空并且没有选定项。