【问题标题】:How to filter / selectively copy values from one DataGridView to another DataGridView如何过滤/有选择地将值从一个 DataGridView 复制到另一个 DataGridView
【发布时间】:2013-05-20 06:38:27
【问题描述】:

我有 2 个 DataGridView:productsDataGridViewpromotionsDataGridView

第一个,productsDataGridView,它使用这种方法从文件中读取ALL值:

public static List<Products> LoadUserListFromFile(string filePath)
{
    var loadProductsData = new List<Products>();

    foreach (var line in File.ReadAllLines(filePath))
    {
        var columns = line.Split('\t');
        loadProductsData.Add(new Products
        {
            InventoryID = "BG" + columns[0],
            Brand = columns[1],
            Category = columns[2],
            Description = columns[3],
            Promotions = Convert.ToInt32(columns[4]),
            Quantity = Convert.ToInt32(columns[5]),
            Price = Convert.ToDouble(columns[6])
        });
    }

    return loadProductsData;
}

第一个 DataGridView (productsDataGridView) 已正确填充所有值。现在在我的 productsDataGridView 中,我设置了一个名为“Promotion”的 check-box 列(Promotion 列从文件中读取整数值):如果它的值为 0 -该框不被选中,如果大于 1:被选中。 现在我想做的是 FILTER/MOVE (我不关心两者中的哪一个)从 productsDataGridViewpromotionsDataGridView 的值在哪里我们在复选框列(促销)中有一个 >0 值。

示例: 如果 productsDataGridView 共有 25 个产品,其中 8 个是促销产品(复选框列中的值 >0),promotionsDataGridView 应填充 8 个值,这些值是从 DataGridView 复制/移动/过滤/任何内容。

到目前为止,我只能使用以下代码将数据从第一个 DataGridView 复制到第二个:

public void Experimental2()
{
    dataGridView1.DataSource = Products.LoadUserListFromFile(filePath);
    //Bind datagridview to linq 
    var dg1 =
        (from a in productsDataGridView.Rows.Cast<DataGridViewRow>()
         select new { Column1 = a.Cells["Column1"].Value.ToString() }).ToList();

    //loop dg1 and save it to datagridview2
    foreach (var b in dg1)
    {
        dataGridView1.Rows.Add(b.Column1);
    }
}

我做了一些可怜的尝试来插入一个 IF 检查,这将为我完成这项工作(仅复制 IF columnt[4] > 0)但我对 DataGridView 真的很陌生,所以我什至无法写任何东西完全编译...

请帮帮我!

【问题讨论】:

标签: c# datagridview filter


【解决方案1】:

如果两个网格具有相同的模式(我假设它们具有),那么我们将找到检查了哪些行,将产品绑定到给定行,创建新的结果列表并将其绑定到下一个网格。

var results = new List<Products>(); //our new data source with only checked items

foreach (DataGridViewRow row in productsDataGridView.Rows)
{
    var item = row.DataBoundItem as Products; //get product from row (only when grid is databound!)

    if (item.Promotions > 0)
    {
        results.Add(item);        
    }
}

promotionsDataGridView.DataSource = results; 

如果您想从第一个网格中删除已检查的行,则创建临时行列表,将已检查的行添加到其中,最后遍历它们并逐个删除。希望能帮到你:)

【讨论】:

  • 顺便说一句:这两个 DGV 并不完全相同。我从第一列中只选择了 5 列。
  • 已编辑,出错,忘记添加.Rows :)。此外,网格不必相同,只有它们的列应该具有相同的数据绑定集
  • 我没有对其进行测试,但我使用了您提供的所有信息(以及一些假设:))。它仍然应该工作得很好。修改了一些代码,请尝试一下。
  • 是的,它有效,哈哈,想象一下我是多么愚蠢...我没有在 FORM_LOAD 中加载方法!... :D 非常喜欢我!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-09-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多