增加过滤按钮的代码来自CodeProject网站,以下为实现步骤:
1.在工程中加入 DataGridViewAutoFilterColumnHeaderCell.vb 和 DataGridViewAutoFilterTextBoxColumn.vb
2.DataGridView中的数据vb.net教程要采用BindingSource的方式来绑定:
Dim dataSource As New BindingSource(table, Nothing) '此种方式可以在栏头过滤
Main.DataViewLib.DataSource = dataSource
同时再加入以下c#教程代码:
' Add the AutoFilter header cell to each column.
For Each col As DataGridViewColumn In Main.DataViewLib.Columns
col.HeaderCell = New DataGridViewAutoFilterColumnHeaderCell
Next
- 3
- 4
以下步骤即可实现增加过滤按钮。为实现过python基础教程滤的栏头有不一样的颜色还需做以下修改:
1.属性EnableHeadersVisualStyles需设为False
DataGridView.EnableHeadersVisualStyles = False
2.在DataGridView的DataBindingComplete事件中增加以下代码
```php
'过滤时控制栏头颜色
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
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
效果如图: