1

我正在尝试在下面运行此代码。它以前可以工作,但是当我添加第二个数据读取器时,它停止了。谁能告诉我怎么了?

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

在此处输入图像描述

你好,

lblUserSelected.Text = "Selected: " + lstUsers.SelectedItem.Text每当我输入用户名并单击搜索时,我都会遇到 NullReference 异常txtUserSearch,它以前可以正常工作..我不知道发生了什么..

谁能告诉我怎么了?

4

1 回答 1

0

我假设你正在NullReferenceException这条线上:

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

因为您没有指定SelectedItem最近填充的ListBox. 要选择第一项,您可以使用以下代码:

While datareader.Read
    lstUsers.Items.Add(datareader.Item("username"))
End While
If lstUsers.Items.Count <> 0 Then lstUsers.SelectedIndex = 0

您也没有处理数据库中没有用户名的情况,那么它ListBox是空的并且没有选定的项目。

于 2013-04-08T13:33:58.890 回答