简体   繁体   English

在DataGridView中搜索字符串并仅使结果可见

[英]Searching for a string in DataGridView and keeping visible only the result

I have a search text box in a form that uses -match . 我有一个使用-match形式的搜索文本框。 A Write-Host shows a positive result when the search matches, but the DataGridView is hidden everything. 当搜索匹配时, Write-Host显示肯定结果,但DataGridView会隐藏所有内容。

I have tried 2 solutions but without success; 我尝试了2种解决方案,但没有成功; both returns "MATCH!!!" 都返回“ MATCH !!!” but all rows become invisible, which is unexpected: 但是所有行都变得不可见,这是意外的:

1st approach: 第一种方法:

foreach ($row in $DataGridView1.Rows) {
    foreach ($cell in $row.Cells) {
        if ($cell.Value.ToString() -match ($searchTextBox.Text)) {
            $DataGridView1.Rows[$row.Index].Visible = $true
            Write-Host "MATCH!!!"
        } else {
            $DataGridView1.Rows[$row.Index].Visible = $false
        }
    }
}

2nd approach: 第二种方法:

for ($i = 0; $i -lt $DataGridView1.RowCount; $i++) {
    for ($j = 0; $j -lt $DataGridView1.ColumnCount; $j++) {
        $CurrentCell = $DataGridView1.Rows[$i].Cells[$j]
        if ($CurrentCell.Value.ToString() -match ($searchTextBox.Text)) {
            $DataGridView1.Rows[$i].Visible = $true
            Write-Host "MATCH!!!"
        } else {
            $DataGridView1.Rows[$i].Visible = $false
        }
    }
}

Looks like both codes are doing $DataGridView1.Rows[$i].Visible = $false every time. 看起来这两个代码每次都在执行$DataGridView1.Rows[$i].Visible = $false

The inner loops of both of your approaches define the visibility of the row for each cell individually. 两种方法的内部循环都分别定义了每个单元格的行可见性。 Unless the last cell in a row produces a match the row will end up hidden, even if a match was found in another cell before. 除非一行中的最后一个单元格产生匹配项,否则即使之前在另一个单元格中找到了匹配项,该行也将最终被隐藏。

What you actually want is set the row visible if a match was found in any of the cells in a row, so you need to remember if a match was already found in the current row, and set the visibility after processing all cells of the row. 您真正想要的是,如果在一行的任何单元格中找到匹配项,则将该行设置为可见,因此您需要记住在当前行中是否已找到匹配项,并处理该行的所有单元格设置可见性。

Change the inner loop to something like this: 将内部循环更改为如下所示:

$found = $false
foreach ($cell in $row.Cells) {
    if ($cell.Value.ToString() -match ($searchTextBox.Text)) {
        $found = $true
        Write-Host "MATCH!!!"
        break
    }
}
$DataGridView1.Rows[$row.Index].Visible = $found

and it should do what you want. 它应该做您想要的。

The additional break in the condition is a performance optimization. 该条件的另一个break是性能优化。 Once a match is found there is no need to test the remaining cells of the row, so you can skip the rest of the loop, set the visibility, and move to the next row. 找到匹配项后,无需测试该行的其余单元格,因此您可以跳过循环的其余部分,设置可见性,然后移至下一行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM