【发布时间】: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