使用VB隐藏DataGridView中的所有行

时间:2019-05-30 16:12:20

标签: vb.net search datagridview

我正在尝试过滤DataGridView中的数据,我需要隐藏所有行和列。我尝试使用循环列表LINQ和lambda表达式来执行此操作,因为如果使用foreach,则在尝试过滤3000行时会很慢。

下面的代码执行没有错误,但没有像我想要的那样隐藏行:

datagrid.Rows.OfType(Of DataGridViewRow)().ToList().ForEach(Function(obj) obj.Visible = False)

我不使用数据集,也不知道是否可以像我尝试的那样解决,或者foreach或外部的错误是什么。

2 个答案:

答案 0 :(得分:0)

您应该绑定数据并对数据本身(而不是用户界面)进行操作。您可以执行以下操作:

Public Class Form1

    Private allData As IEnumerable(Of Data) ' all your data
    Private filtered As IEnumerable(Of Data) ' filtered for logical and display purposes

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        allData = Enumerable.Range(0, 32).Select(Function(i) New Data() With {.Value = i})
        updateFilteredNumbers(Function(d) True) ' filtered list initially identical to all
    End Sub
    Private Sub HideButton_Click(sender As Object, e As EventArgs) Handles HideButton.Click
        updateFilteredNumbers(Function(d) False)
    End Sub
    Private Sub ShowButton_Click(sender As Object, e As EventArgs) Handles ShowButton.Click
        updateFilteredNumbers(Function(d) True)
    End Sub
    Private Sub EvenButton_Click(sender As Object, e As EventArgs) Handles EvenButton.Click
        updateFilteredNumbers(Function(d) d.Value Mod 2 = 0)
    End Sub
    Private Sub OddButton_Click(sender As Object, e As EventArgs) Handles OddButton.Click
        updateFilteredNumbers(Function(d) d.Value Mod 2 = 1)
    End Sub
    Private Async Sub updateFilteredNumbers(predicate As Func(Of Data, Boolean))
        ' perform filtering asynchronously, then update datasource on UI thread
        filtered = Await Task.Factory.StartNew(Function() allData.Where(predicate).ToList())
        datagrid.DataSource = filtered
    End Sub

End Class

Public Structure Data ' Class to represent your data. Simple for this example
    Public Property Value As Integer
End Structure

此示例可以全部隐藏,全部显示或仅显示奇数或偶数。您可以更新“过滤的”集合,而只需刷新数据源。

答案 1 :(得分:0)

这完全可以满足您的需求

Dim dv As DataView
dv = New DataView(ds.Tables(0), "name = 'Devcon' ", "type Desc", DataViewRowState.CurrentRows)
DataGridView1.DataSource = dv