【问题标题】:How to hide a DataGridVew row如何隐藏 DataGridView 行
【发布时间】:2020-08-11 01:51:13
【问题描述】:

在 C# WinForms 项目中,我将 DataGridView 的 DataSource 作为 DataTable 进行迭代,并检查源数据库并确定其中一列中的值是否有效。如果它一个有效值,我想隐藏它,所以我最终只会让 DGV 显示具有无效值的行。

这是我目前所拥有的伪代码。

private void btnValidate_Click(object sender, EventArgs e)
    {
    DataTable dt = ((DataTable)dgvMyDataGridView.DataSource);

    int intRowIndex;

    for (intRowIndex = 0; intRowIndex <= dt.Rows.Count - 1; intRowIndex++)
    {
        DataRow drValidationRow = dt.Rows[intRowIndex];

        string strNewValue = drValidationRow[5].ToString();
        // Get the current row's db record ID as a string for the db query
        int intCurrDgvRowId = int.Parse(dgvMyDataGridView[0, intRowIndex].Value.ToString());

        // Determine if we need to show or hide the DGV's row
        bool bNewValueIsValid = <db check for valid strNewValue>

        if (bNewValueIsValid)
        {
            /*
             *  Hide the DGV row corresponding to the DT row ID
             */
        }
    }
}

我尝试了对我来说最合乎逻辑的方法:

dgvmyDataGridView.Rows[intRowIndex].Visible = false;

但是当我运行它时,我得到了这个错误:

System.InvalidOperationException: 'Row associated with the currency manager's position cannot be made invisible.'

我不能只做 drValidationRow.Visible = false 之类的事情,因为上面没有 Visible 属性,我猜是因为该行来自 DataTable 而不是 DGV。

我该如何做到这一点?

【问题讨论】:

  • AFAIK 您可以使用SuspendBinding,将Visible 设置为false,然后使用ResumeBinding。不过不确定。
  • 您可以将bool(隐藏)列添加到您的数据表中。当它通过/失败验证时,将此列的值设置为真/假,然后只需使用dt.DefaultView.RowFilter = "[MyBoolColumn] = false"。需要时反转,设置.RowFilter = string.Empty 以移除过滤器。当过滤器处于活动状态时,更改 bool Column 的值将立即更新视图(无需执行任何其他操作)。
  • @Shawn,我查看了 JSL 提供的链接并且该链接有效,但我遇到了一种情况,即我最终没有显示任何行,因为所有值都是有效的,这隐藏了 DGV 中的所有行.我的想法是添加一个计数器并将隐藏的行数与 DGV 中的行数进行比较,如果所有行都有效,则只需刷新 DGV。有没有更好的方法来处理这种情况?
  • @marky 我真的不认为我知道你想要实现什么。如果所有值都有效,则不会显示任何内容。对吗?

标签: c# winforms datagridview datatable


【解决方案1】:

您不需要计数器。如果 Rows.Count = 0 ,您可以只刷新 dgv 吗?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-19
    • 1970-01-01
    • 2013-11-20
    • 2016-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多