如何过滤显示在datagridview中的数据库?

时间:2013-09-25 10:12:33

标签: vb.net winforms datagridview

我在表格中有3级访问权限,即STUDENT,ADMIN和INSTRUCTOR。所以我想只展示那些“讲师”。谢谢我只是一个新手编码。

 Me.cboSearchBy.SelectedIndex = 0
        Dim conn As New OleDbConnection
        Dim cmd As New OleDbCommand
        Dim da As New OleDbDataAdapter
        Dim dt As New DataTable
        Dim sSQL As String = String.Empty

        Try

            conn = New OleDbConnection(Get_Constring)
            conn.Open()
            cmd.Connection = conn
            cmd.CommandType = CommandType.Text
            sSQL = "SELECT Username, lname + ', ' + fname + ' ' + mname as name, password FROM Instructor"
            If Me.cboSearchBy.Text = "Name" Then
                sSQL = sSQL & " where lname + ', ' + fname + ' ' + mname like '%" & Me.txtSearch.Text & "%'"
            Else
                sSQL = sSQL & " where Username =" & Me.txtSearch.Text
            End If
            cmd.CommandText = sSQL
            da.SelectCommand = cmd
            da.Fill(dt)

            Me.dtgResult.DataSource = dt
            If dt.Rows.Count = 0 Then
                MsgBox("No record found!")
            End If

        Catch ex As Exception
            MsgBox(ErrorToString)
        Finally
            conn.Close()
        End Try

2 个答案:

答案 0 :(得分:2)

用此替换您的查询部分;

     sSQL = "SELECT Username, lname + ', ' + fname + ' ' + mname as name, password FROM Instructor"
     If Me.cboSearchBy.Text = "Name" Then
        sSQL = sSQL & " where lname + ', ' + fname + ' ' + mname like '%" & Me.txtSearch.Text & "%'"
        sSQL = sSQL & " and  level like '%instructor%'"
     Else
        sSQL = sSQL & " where Username =" & Me.txtSearch.Text
        sSQL = sSQL & " and  level like '%instructor%'"
     End If

答案 1 :(得分:0)

虽然@Nadeem_MK具有首选方法,但让数据库执行最佳操作,有时您需要所有数据,并且需要在本地过滤它(无需再次调用数据库)。一种方法是:

...Your code
da.SelectCommand = cmd
da.Fill(dt)
'Filter locally
dim drs as datarow() = dt.select("level = 'Instructor'")
'Use the datarow array as your datasource instead of the data table
Me.dtgResult.DataSource = drs

或者,如果您使用的是“BindingSource”,也可以对其进行过滤。