【问题标题】:Properly filtering DataGridView DataSource with buttons使用按钮正确过滤 DataGridView 数据源
【发布时间】:2017-06-06 15:27:18
【问题描述】:

主要目标是不改变数据源。所以,当我得到我的结果集时,我想总是根据这个结果集进行过滤。我一直在使用 DataGridView,而预先存在的代码仅限于将行直接添加到 DataGridView 而不是使用 DataTable。

我已经尝试过了,它确实有效,但我觉得它的效率并不高,我想知道是否有不需要循环的最佳解决方案。

这是按下按钮:

for (int i = 0; i < this.dataGridView1.RowCount; i++)
    {
     if (this.dataGridView.Rows[i].Cells[3].Value = "Sleeping Disorder")
     {
       this.dataGridView.Rows[i].Visible = true;
     }
     else
     {
       this.dataGridView.Rows[i].Visible = false;
      }
    }

我进行了一些研究,发现有人在使用 DataTables,但我不允许重新编写整个代码集,所以我想知道是否可以在没有 DataTable 的情况下执行此操作,或者我是否必须使用 DataTable,可以吗?使用一种方法用我的 DataGridView 填充表格并从那里开始?

数据最初来自 MySQL 查询。 谢谢。

【问题讨论】:

  • 网格人口的数据来源是什么?我知道您手动添加行,但数据最初来自哪里?
  • 添加了一个编辑(来自 MySQL 查询)
  • 为什么不使用循环来填充数据表,并将数据表用作数据网格的数据源。比你可以很容易地过滤你的数据表
  • 我个人还是会说使用数据表。这样做不是重新工作。您正在用另一个过滤程序替换一个过滤程序。填充保持数据源完整的数​​据表,然后将网格绑定到数据表。
  • 我明白了,所以如果我走 DataTable 路线,我会做类似 table.DefaultView.RowFilter = string.Format("[Sleeping Disorder] = " + sleepButton.Text);

标签: c# winforms datagridview filter


【解决方案1】:

我用来过滤 DataGrid 的 sn-p

// DevicesGrid is the DataGrid with the data I want to filter
// this next line gets the textbox contents to filter on, you won't need this
Controls.TextBox textbox = sender as Controls.TextBox;
        ICollectionView cvs = CollectionViewSource.GetDefaultView(DevicesGrid.ItemsSource);

   // doing the filter
// A PortResult is what is in the collection, replace that with whatever is in yours
        cvs.Filter = new Predicate<object>(item =>
        {
            PortResult pr = item as PortResult;
            if (pr.Name.Contains(textbox.Text))
            { return true; }
            else { return false; }
        });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-19
    • 2016-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-15
    • 2019-10-18
    相关资源
    最近更新 更多