【问题标题】:Hide all rows that do not match driverNo.Text隐藏所有与 driverNo.Text 不匹配的行
【发布时间】:2013-12-11 18:58:33
【问题描述】:

我想隐藏 datagrid 中与 driverNo.Text 中的文本不匹配的所有行,但是当 driverNo.Text 为空时,我想要所有要出现的数据网格中的行。我将如何做到这一点?

    private void driverNo_KeyUp(object sender, KeyEventArgs e)
    {
        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            if (row.Cells[1].Value.ToString() == driverNo.Text)
            {

            }
            else if (row.Cells[1].Value.ToString() == null)
            {

            }
        }
    }

【问题讨论】:

  • 更好的方法可能是过滤数据源。这是绑定网格吗?如果您绑定到 DataView,您可以使用它的 filter 属性。在上面,您可以将行高设置为 0,但它不会完全消失。例如row.Height = 0

标签: c# winforms datagrid


【解决方案1】:

这应该可以解决问题:

CurrencyManager manager = (CurrencyManager)BindingContext[dataGridView1.DataSource];
manager.SuspendBinding();
bool shouldNotFilter = string.IsNullOrEmpty(driverNo.Text);
foreach (DataGridViewRow row in dataGridView1.Rows)
{
    if (shouldNotFilter)
    {
        row.Visible = true;
    }
    else
    {
        if (!string.Equals(row.Cells[1].Value.ToString(), driverNo.Text, StringComparison.OrdinalIgnoreCase))
        {
            row.Visible = false;
        }
        else
        {
            row.Visible = true;
        }
    }
}
manager.ResumeBinding();

这种方法直截了当但速度很慢,我建议您查看DataView 及其RowFilter 属性。 Here 就是一个很好的例子。

【讨论】:

  • 嗨 Yuriy - 感谢您的帮助。我已经尝试过上面的代码,每次我输入任何大于 1 的数字时,它都会使我的应用程序崩溃并显示错误消息:An unhandled exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll. Additional information: Row associated with the currency manager's position cannot be made invisible.
  • @Antoine-LaurentLavoisier,我怀疑您正在以下列方式使用CurrencyManager CurrencyManager manager = (CurrencyManager)BindingContext[datagridview1.DataSource]; 您可以分别在提供的代码manager.SuspendBinding();manager.ResumeBinding(); 之前和之后添加以下行。这应该可以解决问题,但这不是一个好的解决方案,我建议看看DataView。希望这会有所帮助。
  • 您能否更新答案以反映它 - 这就是我的代码目前的样子 - pastebin.com/xNGgsdKi
  • 谢谢 Yuriy - 快速提问。每当我按退格键时,代码似乎都会停止搜索行,例如当我输入 12 然后在 2 上退格并离开 1 时,它不再拾取 1
  • @Antoine-LaurentLavoisier, KeyUp 事件不会针对某些键引发,因此您可以将您的逻辑连接到 TextChanged 事件。
【解决方案2】:

这可能不是您所需要的,而是类似的东西?

private void driverNo_KeyUp(object sender, KeyEventArgs e)
{
    // Set all rows.Visible = false in design
    if (driverNo.Text = "")
    {
        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            row.Visible = true;
        }
    }
    else
    {
        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            if (row.Cells[1].Value.ToString() == driverNo.Text)
            {
                row.Visible = true;
            }
        }
    }
}

如果 driverNo.Text 为空,这将使所有行可见,否则仅显示 driverNo.Text 中包含的行。

注意:行开始时不需要可见,或者您可以使它们开始可见,只需将 if 语句更改为 != driverNo.Text 并设置为 false

【讨论】:

猜你喜欢
  • 2010-10-26
  • 2011-02-08
  • 2016-09-08
  • 1970-01-01
  • 2011-10-09
  • 1970-01-01
  • 2013-02-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多