使用C#WindowsForms,
我有2个Datagridviews,每个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);
}
}
答案 0 :(得分:0)
您应该比较绑定到DataGrid的数据,这比访问网格本身的属性更好。