VB.net ListBox从访问数据库获取类似的数据,但是当我单击它时,它仅显示最后一条记录

时间:2018-07-05 14:24:56

标签: vb.net ms-access listbox

该程序运行良好,但是当涉及到类似数据时,搜索会找到它们并将它们列出到ListBox中,但是当我单击以在TextBox或RichTextBox上显示它们时,它仅显示数据库的最后一条记录。

我想要从MS Access数据库中获取相似数据并将其显示到TextBox。
有关更多详细信息,我有屏幕截图。
enter image description here

代码是:

Imports System.Data.OleDb

Public Class Form1

Dim Con As OleDbConnection

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim sString As String = "Provider=Microsoft.Jet.OleDb.4.0;Data Source=system\default.mdb"
    Con = New OleDbConnection
    Con.ConnectionString = sString
    If Not Con.State = ConnectionState.Open Then
        Con.Open()
    End If
End Sub

Private Sub dbLoad()
    If (TextBox1.Text = "") Then
        TextBox2.Text = ":)"
    Else
        Try
            Dim cmd As New OleDbCommand("select * from data where name like '" & TextBox1.Text & "' ", Con)
            Dim rdr As OleDbDataReader
            rdr = cmd.ExecuteReader
            If rdr.HasRows Then
                While rdr.Read
                    TextBox2.Text = CStr(rdr("info"))
                End While
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        Finally
        End Try
    End If
End Sub

Private Sub FillListBox()
    If Len(TextBox1.Text) > 0 Then
        Dim cmd As New OleDbCommand("select * from data where name like '" & TextBox1.Text & "%' ", Con)
        Dim rdr As OleDbDataReader
        rdr = cmd.ExecuteReader
        cmd.Dispose()
        ListBox1.Items.Clear()
        If rdr.HasRows Then
            While rdr.Read
                ListBox1.Items.Add(rdr("name"))
            End While
        End If
        rdr.Close()
    Else
        ListBox1.Visible = True
    End If
End Sub

Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
    Dim cmd As New OleDbCommand("select * from data where name like '" & ListBox1.Text & "' ", Con)
    Dim rdr As OleDbDataReader
    rdr = cmd.ExecuteReader
    cmd.Dispose()
    If rdr.HasRows Then
        While rdr.Read
            TextBox2.Text = CStr(rdr("info"))
        End While
    End If
    rdr.Close()
End Sub

Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
    dbLoad()
    FillListBox()
End Sub
End Class

我很感谢大家能帮助我。
预先感谢。

1 个答案:

答案 0 :(得分:0)

它仅显示一条记录,因为您在每次迭代中都覆盖了文本框:

If rdr.HasRows Then
    Dim builder as New System.Text.StringBuilder("")
     While rdr.Read
         builder.AppendLine(CStr(rdr("info")))
     End While
     TextBox2.Text = builder.ToString()
 End If

使用StringBuilder获取所有内容并立即显示。