2013-03-28 66 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中可見,並在打印後進行比較 –