如何通过文本框在数据库中搜索记录,并将其显示在列表视图中

时间:2014-01-28 02:40:52

标签: vb.net

这是我的搜索代码,当我运行它并尝试在文本框中搜索时。列表视图变空。

        Dim SqlQuery As String = "SELECT * FROM sample WHERE FirstName like ' % " & TextBox4.Text & " % ' "
        Dim SqlCommand As New OleDbCommand
        Dim SqlAdapter As New OleDbDataAdapter
        Dim TABLE As New DataTable
        'MsgBox("trigger")

        With SqlCommand
            .CommandText = SqlQuery
            .Connection = conn

        End With

        With SqlAdapter
            .SelectCommand = SqlCommand
            .Fill(TABLE)
        End With

        ListView1.Items.Clear()
        For i = 0 To TABLE.Rows.Count - 1
            With ListView1
                .Items.Add(TABLE.Rows(i)("ID"))
                With .Items(.Items.Count).SubItems
                    .Add(TABLE.Rows(i)("FirstName"))
                    .Add(TABLE.Rows(i)("MiddleName"))
                    .Add(TABLE.Rows(i)("LastName"))
                    .Add(TABLE.Rows(i)("Gender"))
                End With
            End With
        Next
    End Sub

请帮帮我。我的论文真的需要它,而且我是编程的新手。

2 个答案:

答案 0 :(得分:0)

试试这个

 Dim SqlQuery As String = "SELECT * FROM sample WHERE FirstName like ' % " & TextBox4.Text & " % ' "
        Dim SqlCommand As New OleDbCommand
        Dim SqlAdapter As New OleDbDataAdapter
        Dim TABLE As New DataTable
        'MsgBox("trigger")

        With SqlCommand
            .CommandText = SqlQuery
            .Connection = conn

        End With

        With SqlAdapter
            .SelectCommand = SqlCommand
            .Fill(TABLE)
        End With

        ListView1.Items.Clear()
        For i = 0 To TABLE.Rows.Count - 1
           Dim li As new ListViewItem
                li=ListView1.Items.Add(TABLE.Rows(i)("ID").ToString())
                li.SubItems.Add(TABLE.Rows(i)("FirstName").ToString())
                li.SubItems.Add(TABLE.Rows(i)("MiddleName").ToString())
                li.SubItems.Add(TABLE.Rows(i)("LastName").ToString())
                li.SubItems.Add(TABLE.Rows(i)("Gender").ToString())
        Next

答案 1 :(得分:0)

看起来你没有宣称我是整数

Dim SqlQuery As String = "SELECT * FROM sample WHERE FirstName like ' % " & TextBox4.Text & " % ' "
        Dim SqlCommand As New OleDbCommand
        Dim SqlAdapter As New OleDbDataAdapter
        Dim TABLE As New DataTable
   ---->Dim I as Integer
        'MsgBox("trigger")

    With SqlCommand
        .CommandText = SqlQuery
        .Connection = conn

    End With

    With SqlAdapter
        .SelectCommand = SqlCommand
        .Fill(TABLE)
    End With

    ListView1.Items.Clear()
    For i = 0 To TABLE.Rows.Count - 1
       Dim li As new ListViewItem
            li=ListView1.Items.Add(TABLE.Rows(i)("ID").ToString())
            li.SubItems.Add(TABLE.Rows(i)("FirstName").ToString())
            li.SubItems.Add(TABLE.Rows(i)("MiddleName").ToString())
            li.SubItems.Add(TABLE.Rows(i)("LastName").ToString())
            li.SubItems.Add(TABLE.Rows(i)("Gender").ToString())
    Next