VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > VB.net教程 >
  • VB.Net为DataGridView增加过滤按钮

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

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

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


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

同时再加入以下代码:


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

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

1.属性EnableHeadersVisualStyles需设为False

 DataGridView.EnableHeadersVisualStyles = False

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


  1.  
    '过滤时控制栏头颜色
  2.  
    Private Sub DataViewLib_DataBindingComplete(sender As System.Object, e As System.Windows.Forms.DataGridViewBindingCompleteEventArgs) Handles DataViewLib.DataBindingComplete
  3.  
    'Dim filterStatus As String = DataGridViewAutoFilterColumnHeaderCell.GetFilterStatus(DataViewLib) '获得过滤数量状态
  4.  
    Dim data As BindingSource = DataViewLib.DataSource
  5.  
    If Not data.Filter Is Nothing Then '若有过滤
  6.  
    For i As Integer = 0 To DataViewLib.Columns.Count - 1 '给所有栏头设置初始颜色
  7.  
    DataViewLib.Columns(i).HeaderCell.Style.BackColor = System.Drawing.SystemColors.Control
  8.  
    Next
  9.  
     
  10.  
    Dim tempFilter As String = data.Filter
  11.  
    Dim tempColumName As String = ""
  12.  
    For i As Integer = 0 To data.Filter.Length - 1
  13.  
    If tempFilter.IndexOf("]") >= 0 Then
  14.  
    tempColumName = tempFilter.Substring(tempFilter.IndexOf("[") + 1, tempFilter.IndexOf("]") - tempFilter.IndexOf("[") - 1)
  15.  
    tempFilter = tempFilter.Remove(0, tempFilter.IndexOf("]") + 1) '如果未找到“]”此行则会出错退出此函数
  16.  
    DataViewLib.Columns(tempColumName).HeaderCell.Style.BackColor = Color.Yellow
  17.  
    Else
  18.  
    Exit For '提前退也循环
  19.  
    End If
  20.  
    Next
  21.  
    End If
  22.  
    DataViewLib.ClearSelection() '防止默认选择
  23.  
    End Sub
 

效果如图:


相关教程