locked
FAQs:怎样在数据库中搜索和过滤数据集? RRS feed

答案

  • 2种方式:

    1)  T-SQL语句

    在窗体上拖一个DataGridViewTextBox

     

    Imports System.Data.OleDb

    Public Class Form1

        ' 处理 TextBox_TextChanged 事件

        Private Sub TextBox1_TextChanged(ByVal sender As System.Object, _

                             ByVal e As System.EventArgs) Handles TextBox1.TextChanged

            Dim keywords As String = TextBox1.Text

            Dim con As OleDbConnection = New OleDbConnection( _

                             "Provider=Microsoft.jet.oledb.4.0;data source=D:\myDB.mdb")

            Dim cmd As OleDbCommand = New OleDbCommand( _

                             "SELECT * FROM Table1 WHERE Filed1 Like '%" & keywords & "%' ", con)

            ' 或者 Where Filed1='" & keywords & "'  

            con.Open()

            Dim myDA As OleDbDataAdapter = New OleDbDataAdapter(cmd)

            Dim myDataSet As DataSet = New DataSet()

            myDA.Fill(myDataSet, "MyTable")

            DataGridView1.DataSource = myDataSet.Tables("MyTable").DefaultView

        End Sub

    End Class

     

    2)  使用 DataGridView.RowFilter 属性

     

    Imports System.Data.OleDb

    Public Class Form1

        Dim ds As DataSet

        Private Sub Form1_Load(ByVal sender As System.Object, _

                          ByVal e As System.EventArgs) Handles MyBase.Load

            Dim con As OleDbConnection = New OleDbConnection( _

                          "Provider=Microsoft.jet.oledb.4.0;data source=D:\myDB.mdb")

            Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM Table1", con)

            con.Open()

            Dim myDA As OleDbDataAdapter = New OleDbDataAdapter(cmd)

            ds = New DataSet()

            myDA.Fill(ds, "MyTable")

            con.Close()

            DataGridView1.DataSource = ds.Tables("MyTable").DefaultView

        End Sub

        Private Sub TextBox1_TextChanged(ByVal sender As System.Object, _

                             ByVal e As System.EventArgs) Handles TextBox1.TextChanged

            Dim keywords As String = TextBox1.Text

            ds.Tables("MyTable").DefaultView.RowFilter = "Field1 =" & keywords

            ' 或者  = "Field1 Like '%" & keywords & "%' "  

        End Sub

    End Class


    如果您对我们的论坛在线支持服务有任何的意见或建议,请通过邮件告诉我们。
    MSDN 论坛好帮手 立刻免费下载  MSDN 论坛好帮手
    2011年3月3日 2:17