Home > DeveloperSection > Forums > Compare 2 datagridview's
Erik Pasmar
Erik Pasmar

Total Post:1

Points:7
Posted on    February-13-2014 2:11 AM

 C# C# 
Ratings:


 1 Reply(s)
 1179  View(s)
Rate this:
Hi. I have a problem with compareing. i made code to compare if values are same copy them to datagridview3. But now i need to copy them to datagridview4 if they are not same (  datagridview1 != datagridview2)  

//pobarvaj
            var style1 = this.dataGridView1.DefaultCellStyle.Clone();
            style1.BackColor = Color.Green;
            var style2 = this.dataGridView2.DefaultCellStyle.Clone();
            style2.BackColor = Color.Blue;
            //primerjaj
       
            var duplicateTable = (dataGridView2.DataSource as DataTable).Clone();

            // iterating the DataGridView rows to get the right order
            foreach (DataGridViewRow viewRow1 in this.dataGridView1.Rows)
            {
                bool isDuplicate = false;
                DataRowView row1 = viewRow1.DataBoundItem as DataRowView;
                if (row1 != null && viewRow1.DefaultCellStyle != style1)
                {
                    foreach (DataGridViewRow viewRow2 in this.dataGridView2.Rows)
                    {
                        DataRowView row2 = viewRow2.DataBoundItem as DataRowView;
                        
                        if (row2 != null && row1.Row["cel1"].Equals(row2.Row["cel2"]))
                   
                        {
                           
                            if (viewRow2.DefaultCellStyle != style2)
                            {
                                
                                duplicateTable.Rows.Add(row2.Row.ItemArray);
                            }

                            isDuplicate = true;
                            viewRow2.DefaultCellStyle = style2;
                        }
                    }
                }
                if (isDuplicate)
                {
                    viewRow1.DefaultCellStyle = style1;
                    this.dataGridView3.DataSource = duplicateTable;
                }
            }


Sumit Kesarwani

Total Post:378

Points:2694
Posted on    February-16-2014 11:44 PM

Hi Erik,

First get the datatables of both the datagridview and compare them using the following method and set the datatable as datasource upon your condition : 

public bool compareTbls(Datatable tbl1, Datatable tbl2)
{
  if(tbl1.Rows.Count != tbl2.Rows.Count || tbl1.Columns.Count != tbl2.Columns.Count)
    return false;

  for(int i = 0; i < tbl1.Rows.Count; i++)
  {
    for(int c = 0; c < tbl.Columns.Count; c++)
    {
      if(tbl1.Rows[i][c] != tbl2.Rows.Columns[i][c])
        return false;
    }
  }
  return true;
}

Hope this will solve your problem.

Modified On Feb-16-2014 11:45:23 PM

Don't want to miss updates? Please click the below button!

Follow MindStick