1)
如果你想使用一個for循環是不明智的這條線還增加索引變量的代碼通過集合迭代:
i++;
它已經增加。所以當你穿過dataGridView2
時,你實際上還會在dataGridView1
之間滑動一個位置。這不是你想要的(正如我從你的帖子中看到的,你描述了所需的比較)。您需要刪除此行
2)
我想比較:1對3,1對4,2比3,2比4,3比3,3比4。
如果你想只比較name
列那麼你的索引是正確的:
dataGridView2.Rows[j].Cells[1]
,但如果你想比較Id列則是因爲索引編制從0
開始。因此,要獲得從Id
列,你必須使用這樣的正確的值:
string grid2 = dataGridView2.Rows[j].Cells[0].Value.ToString();
與此相比在您若條件:
dataGridView2.Rows[0].Cells[1].Value.ToString() == dataGridView1.Rows[0].Cells[1].Value.ToString()
你還用C
比較A
。我沒有看到任何理由(將你的描述作爲比較的願望)。你可以擺脫它。
3)
如果你想改變一個集合的大小(通過刪除,通過它你迭代它是明智的使用元素)反向for循環從dataGridView2.RowCount-1
開始,一直持續到>= 0
。否則,您可能會遇到ArgumentOutOfBounds
異常,因爲除去啓動循環時所用的元素並不多。結束索引處的元素將不再存在。
for (int i = dataGridView1.RowCount-1; i >= 0 ; i--)
{
for (int j = 0; j < dataGridView2.RowCount; j++)
{
string grid2 = dataGridView2.Rows[j].Cells[0].Value.ToString();
string grid1 = dataGridView1.Rows[i].Cells[0].Value.ToString();
if (grid1 == grid2)
{
dataGridView1.Rows.RemoveAt(i);
}
}
}
編輯:
的dataGridView1
可能會顯示額外的空行這也是在這種情況下,你需要從i = dataGridView1.RowCount-2
開始計入dataGridView1.RowCount
。同樣在你找到一個匹配並從dataGridView1
中刪除該行之後,進一步搜索該行的匹配是沒有意義的,因爲它已經消失。所以你應該跳出內部循環,繼續下一行:
for (int i = dataGridView1.RowCount - 2; i >= 0; i--)
{
for (int j = 0; j < dataGridView2.RowCount -1; j++)
{
string grid2 = dataGridView2.Rows[j].Cells[0].Value.ToString();
string grid1 = dataGridView1.Rows[i].Cells[0].Value.ToString();
if (grid1 == grid2)
{
dataGridView1.Rows.RemoveAt(i);
break;
}
}
}
嘗試在內部循環中刪除增量語句(i ++;)。你增加你的變量我兩次。 – missellorin
嗯,如果我刪除它,它不起作用(它只顯示值,當我= 0和停止)。 –
「只顯示數值」你在哪裏顯示數值?你不是在刪除值嗎? –