我有两个网格视图,我需要按列比较结果。有时,其中一个网格视图可能包含不在另一个网格视图中的列,因此我只需要比较两个网格中存在的列。
我编写的代码实际上遍历每一行的每个单元格,它从第0行单元格0开始并继续第0行单元格1然后转到下一行。但是,我希望以一种方式单元格,如果Grid 2中的列存在于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);
}
}
}
}
}
答案 0 :(得分:1)
我建议你比较两个GridViews的两个DataTable,非常容易。
Yous可以在DataTable.Rows
上使用不同的方法,例如:Contains, Find or CopyTo
link: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"]);
}
}
}
}