0

我有两个网格视图,我需要按列比较结果。有时,其中一个网格视图可能具有不在另一个网格中的列,因此我只需要比较两个网格中都存在的那些列。

我编写的代码实际上遍历了每一行的每个单元格,它从第 0 行单元格 0 开始并继续第 0 行单元格 1,然后进入下一行。但是,我想以某种方式将其设置为单元格,如果说网格 2 中的列存在于网格 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);
                }
            }
        }
    }
}
4

1 回答 1

1

我建议你比较两个 GridView 中的两个 DataTable,这很容易。

您可以使用不同的方法,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"]);
        }
        }
    }
    }
于 2013-03-28T13:13:11.880 回答