VB.Net为DataGridView增加过滤按钮

前端之家收集整理的这篇文章主要介绍了VB.Net为DataGridView增加过滤按钮前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

增加过滤按钮的代码来自CodeProject网站,以下为实现步骤:

1.在工程中加入 DataGridViewAutoFilterColumnHeaderCell.vb 和 DataGridViewAutoFilterTextBoxColumn.vb

2.DataGridView中的数据要采用BindingSource的方式来绑定:

        Dim dataSource As New BindingSource(table,Nothing)  '此种方式可以在栏头过滤
        Main.DataViewLib.DataSource = dataSource

同时再加入以下代码

        ' Add the AutoFilter header cell to each column.
        For Each col As DataGridViewColumn In Main.DataViewLib.Columns
            col.HeaderCell = New DataGridViewAutoFilterColumnHeaderCell
        Next

以下步骤即可实现增加过滤按钮。为实现过滤的栏头有不一样的颜色还需做以下修改

1.属性EnableHeadersVisualStyles需设为False

 DataGridView.EnableHeadersVisualStyles = False

2.在DataGridView的DataBindingComplete事件中增加以下代码

    '过滤时控制栏头颜色
    Private Sub DataViewLib_DataBindingComplete(sender As System.Object,e As System.Windows.Forms.DataGridViewBindingCompleteEventArgs) Handles DataViewLib.DataBindingComplete
        'Dim filterStatus As String = DataGridViewAutoFilterColumnHeaderCell.GetFilterStatus(DataViewLib)  '获得过滤数量状态
        Dim data As BindingSource = DataViewLib.DataSource
        If Not data.Filter Is Nothing Then  '若有过滤
            For i As Integer = 0 To DataViewLib.Columns.Count - 1  '给所有栏头设置初始颜色
                DataViewLib.Columns(i).HeaderCell.Style.BackColor = System.Drawing.SystemColors.Control
            Next

            Dim tempFilter As String = data.Filter
            Dim tempColumName As String = ""
            For i As Integer = 0 To data.Filter.Length - 1
                If tempFilter.IndexOf("]") >= 0 Then
                    tempColumName = tempFilter.Substring(tempFilter.IndexOf("[") + 1,tempFilter.IndexOf("]") - tempFilter.IndexOf("[") - 1)
                    tempFilter = tempFilter.Remove(0,tempFilter.IndexOf("]") + 1)  '如果未找到“]”此行则会出错退出函数
                    DataViewLib.Columns(tempColumName).HeaderCell.Style.BackColor = Color.Yellow
                Else
                    Exit For  '提前退也循环
                End If
            Next
        End If
        DataViewLib.ClearSelection()  '防止默认选择
    End Sub


效果如图:

原文链接:/vb/257716.html

猜你在找的VB相关文章