Click here to Skip to main content
15,891,033 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
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
Posted
Updated 3-Dec-17 9:51am
v5

1 solution

try this
it will handle for any number of cols
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);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900