Member 12457690 Ответов: 1

Как сравнить значения столбцов 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());


Что я уже пробовал:

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

1 Ответов

Рейтинг:
0

Karthik_Mahalingam

попробовать это
он будет обрабатывать любое количество колов

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);