【问题标题】:Programmatically modify cells in a filtered datagridview以编程方式修改过滤后的 datagridview 中的单元格
【发布时间】:2017-06-29 08:40:16
【问题描述】:

如果我从数据源加载 DataGridView,

this.exampleTableAdapter.Fill(this.refdataDataSet.Example);

通过绑定源应用过滤器

exampleBindingSource.Filter = "TrackingId = 'x'";

然后尝试遍历过滤后的DataGridView并修改它们

foreach (DataGridViewRow row in datagridExampleList.Rows)
{
   //Tried to set rows directly
   row.Cells["TrackingId"].Value = "";
   //Also tried variations of setting the DataBoundItem directly
}

但是,由于某种原因,它不会遍历整个集合。

当我调试时,我得到返回的 Rows 集合(使用与过滤器匹配的 x 项过滤),但是当我更改集合中的值(特别是作为过滤器目标的值)时,集合会即时更改并且即使过滤器被挂起并且列表更改事件已设置为 false,迭代也会丢失项目。

似乎没有任何效果..

有什么建议吗?

【问题讨论】:

  • 设置过滤条件后,DataView 将隐藏那些不满足条件的行,它们在迭代中变得不可见。但是,如果您无论如何都需要遍历所有行,那么您可以在迭代之前将 Filter 属性设置为 null,然后在完成迭代后将其恢复。但是您说您正在遍历 DataGridView 的行。请提供您的代码,以便我们重现问题。
  • 感谢 Bahrom(指环王?) - 我为我的问题添加了更多信息,我基本上创建了一个最小的项目,并且可以在各种情况下多次重现(不愿说错误)问题。基本上,Winforms,任何数据源,将一个数据网格视图拖到表面上,一个按钮将数据过滤为您喜欢的任何内容,另一个按钮将过滤后的项目重置回来

标签: c# datagridview bindingsource


【解决方案1】:

以下代码必须让您更改所有行。

            var filter = exampleBindingSource.Filter;
            exampleBindingSource.Filter = null;
            foreach (DataGridViewRow row in datagridExampleList.Rows)
            {
                //Tried to set rows directly
                row.Cells["TrackingId"].Value = "";
                //Also tried variations of setting the DataBoundItem directly
            }
            exampleBindingSource.Filter = filter;

【讨论】:

    【解决方案2】:

    为避免使用行枚举器,您可以尝试使用 for 循环:

    int c = datagridExampleList.Columns["TrackingId"].Index;
    
    for (int r = datagridExampleList.RowCount - 1; r >= 0; r--)
        datagridExampleList[c, r].Value = "";
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-21
      • 2010-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多