本文介绍了如何比较每行中的dataggridview1和datagridview2列值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
int x = 0;
int y = 0;
int i = -1;
int z = 0;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
i++;
if ((dataGridView1.Rows[i].Cells[i].Value) == (dataGridView2.Rows[i].Cells[i].Value))
{
x++;
}
else
{
y++;
}
if (z < dataGridView2.Rows.Count)
{
z++;
}
if (z == dataGridView2.Rows.Count)
{
z--; //subtract 1 from the total count because the datagrid is 0 index based.
}
MessageBox.Show("Matched: " + x.ToString() + "\r\n" + "Not Matched: " + y.ToString());
我的尝试:
What I have tried:
Need code to show if one datagridview has different string than the other by columns.
Gridview 1 Gridview2
Col1 Col1
John John match
Mark Sam Don't match
This is the code I'm trying to get in C# windows for to compare two data Gridviews
推荐答案
int matchedCount = 0;
int unMatchedCount = 0;
int dgv1RowsCount = dataGridView1.Rows.Count;
int dgv2RowsCount = dataGridView2.Rows.Count;
int dgv1ColsCount = dataGridView1.Columns.Count;
int dgv2ColsCount = dataGridView2.Columns.Count;
int minRows = dgv1RowsCount <= dgv2RowsCount ? dgv1RowsCount : dgv2RowsCount;
int minCols = dgv1ColsCount <= dgv2ColsCount ? dgv1ColsCount : dgv2ColsCount;
int maxRows = dgv1RowsCount >= dgv2RowsCount ? dgv1RowsCount : dgv2RowsCount;
int maxCols = dgv1ColsCount >= dgv2ColsCount ? dgv1ColsCount : dgv2ColsCount;
for (int i = 0; i < minRows; i++)
for (int j = 0; j < minCols; j++)
if (dataGridView1.Rows[i].Cells[j].Value == dataGridView2.Rows[i].Cells[j].Value)
matchedCount++;
else
unMatchedCount++;
int extraRows = (dgv1RowsCount != dgv2RowsCount) ? Math.Abs(dgv1RowsCount - dgv2RowsCount) : 0;
int extraCols = (dgv1ColsCount != dgv2ColsCount) ? Math.Abs(dgv1ColsCount - dgv2ColsCount) : 0;
int extraUnMatched = extraRows * maxCols;
extraUnMatched += extraCols * maxRows;
unMatchedCount += extraUnMatched;
MessageBox.Show("Matched: " + matchedCount+ "\r\n" + "Not Matched: " + unMatchedCount);
这篇关于如何比较每行中的dataggridview1和datagridview2列值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!