2013-03-28 32 views
0

我有两个gridviews,我需要按列比较结果。有时候一个gridviews可能有不在另一个的列,因此我只需要比较两个网格中存在的列。比较Gridview列

我写的代码实际上遍历每行的每个单元格,它从行0单元格0开始并继续行0单元格1,然后进入下一行。但是,我希望单元格的方式是,如果Grid 1中存在的列存在于Grid 1中,我会通过它的单元格,然后传递到下一列。下面是我的代码:

List<String> columnsGrid43 = new List<String>(); 

foreach (TableCell cell in gridReport43.Rows[0].Cells) 
{ 
    BoundField fieldGrid43 = (BoundField)((DataControlFieldCell)cell).ContainingField; 
    columnsGrid43.Add(fieldGrid43.DataField); 
} 

foreach (TableCell cell in gridReport44.Rows[0].Cells) 
{ 
    BoundField fieldReportGrid44 = (BoundField)((DataControlFieldCell)cell).ContainingField; 
    if (columnsGrid43.Contains(fieldReportGrid44.DataField)) 
    { 
     for (int countRow = 0; countRow < gridReport44.Rows.Count; countRow++) 
     { 
      for (int countCell = 0; countCell < gridReport44.Rows[countRow].Cells.Count; countCell++) 
      { 
       string grid1Value = gridReport43.Rows[countRow].Cells[countCell].Text; 
       string grid2Value = gridReport44.Rows[countRow].Cells[countCell].Text; 
       if (grid2Value.Contains(grid1Value)) 
       { 
        gridReport43.Rows[countRow].Cells[countCell].BackColor = Color.FromArgb(101, 226, 75); 
        gridReport44.Rows[countRow].Cells[countCell].BackColor = Color.FromArgb(101, 226, 75); 
       } 
       else 
       { 
        gridReport43.Rows[countRow].Cells[countCell].BackColor = Color.FromArgb(255, 102, 102); 
        gridReport44.Rows[countRow].Cells[countCell].BackColor = Color.FromArgb(255, 102, 102); 
       } 
      } 
     } 
    } 
} 

回答

1

我建议你比较两个GridViews中的两个DataTables,很容易。

你要跟可以DataTable.Rows使用型动物的方法,如:Contains, Find or CopyTo

链路:代码http://msdn.microsoft.com/fr-fr/library/system.data.datarowcollection.aspx

这里样品:

public static void CompareRows(DataTable table1, DataTable table2) 
    { 
    foreach (DataRow row1 in table1.Rows) 
    { 
     foreach (DataRow row2 in table2.Rows) 
     { 
     var array1 = row1.ItemArray; 
     var array2 = row2.ItemArray; 

     if (array1.SequenceEqual(array2)) 
     { 
      Console.WriteLine("Equal: {0} {1}", row1["ColumnName"], row2["ColumnName"]); 
     } 
     else 
     { 
      Console.WriteLine("Not equal: {0} {1}", row1["ColumnName"], row2["ColumnName"]); 
     } 
     } 
    } 
    } 
+0

确定当前按钮点击我结合电网1至数据表和绑定网格2到数据表,所以在绑定之前,我应该去比较,然后将修改后的数据表绑定到其中一个网格 – krafo

+0

在绑定之前,chris完全正确操作比较,您还可以存储您的ta在ViewState或Session中可见,并在打印后进行比较 –