【问题标题】:Comparing Datagridview row data with multiple columns将 Datagridview 行数据与多列进行比较
【发布时间】:2017-10-02 13:07:55
【问题描述】:

使用 C# WindowsForms,

我有 2 个 Datagridview,每个 Datagridview 有 2 列。

我想比较 DT1 和 DT2 行,如果在 DT2 行(Col1 和 Col2)中找到 DT1(Col1 和 Col2),则 DT1 行和 DT2 行将被删除/删除。

Diagram of the explained above

Error Row index provided is out of range

Code Start Here
{
        bool MatchFound = false;

        List<int> IndexToRemoveFromGrid = new List<int>();


        //Loop Table 1 and get Row Values for Col1+Col2
        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            DataGridViewRow T1Col1row = dataGridView1.Rows[row.Index];
            DataGridViewRow T1Col2row = dataGridView1.Rows[row.Index];
            string T1Col1RX = (string)T1Col1row.Cells[0].Value + (string)T1Col1row.Cells[1].Value;

            MatchFound = false;

            //Loop Table 2 and get Row Values for Col1+Col2
            foreach (DataGridViewRow rowT2 in dataGridView2.Rows)
            {
                DataGridViewRow T2Col1row = dataGridView2.Rows[rowT2.Index];
                DataGridViewRow T2Col2row = dataGridView2.Rows[rowT2.Index];
                string T2Col1RX = (string)T2Col1row.Cells[0].Value + (string)T2Col1row.Cells[1].Value;

                if (MatchFound == false)
                {
                    //Compare Table 1 RX to Table2 RX , If matched then deleted row on both sides
                    if (String.Compare(T1Col1RX, T2Col1RX, false) == 0)
                    {
                        if (row.Index > -1 && rowT2.Index > -1)
                        {
                            IndexToRemoveFromGrid.Add(row.Index);
                        }
                        MatchFound = true;
                    }
                }
            }
        }

        for (int i = 0; i <= IndexToRemoveFromGrid.Count(); i++)
        {
            dataGridView1.Rows.RemoveAt(i);
            dataGridView2.Rows.RemoveAt(i);
        }
    }

【问题讨论】:

  • Datagridviews 有数据集合,只需比较内容并从容器中删除不必要的。
  • 我写了这篇文章,但是我遇到了索引值、返回 -1 和异常的问题
  • 你遇到了什么异常,什么时候发生的?
  • 我解决了异常,我的循环有问题,但是我修复了它。我现在的问题是,当我第一次运行时它会删除行,当我再次运行时它会删除更多行,即使它们的值不同

标签: c# winforms datagridview


【解决方案1】:

您应该比较绑定到 DataGrid 的数据,这比访问网格本身的属性要好。

【讨论】:

  • 我设法达到了一个好的点,但是我遇到了一个错误,点击我附上屏幕截图的错误链接。现在我知道每次我删除索引号时,整个索引号都会移动,例如我有 1324 索引并且错误发生在 662 上,这是一半所以我不知道如何解决它,有点帮助会很棒
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-25
  • 1970-01-01
  • 1970-01-01
  • 2020-12-30
相关资源
最近更新 更多