将每个列单元格值与行中的下一个列单元格值进行比较

时间:2019-08-08 08:01:22

标签: c# asp.net gridview

如果我有一个DataGridView,我需要将单元格的值与另一个单元格进行比较?

详细信息: 我需要将每个单元格的值与左侧相邻单元格中的值进行比较。

下面是我想做的功能和逻辑:

protected void gdData_RowDataBound(object sender, GridViewRowEventArgs e)
{
    //Loop IS REQUIRED NEED HELP ON HOW TO STRUCTURE IT TO Compare 
    //values of 1st cell to the next cell
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        if (e.Row.Cells[2] < e.Row.Cells[3])
            e.Row.Cells[2].ForeColor = System.Drawing.ColorTranslator.FromHtml("#FF0000");
        else
            e.Row.Cells[2].ForeColor = System.Drawing.ColorTranslator.FromHtml("#008000");
    }
}

1 个答案:

答案 0 :(得分:0)

您需要比较源数据(而不是单元格)中的值。请注意,gv.Columns.Count仅适用于TemplateField和BoundField,不适用于自动生成的列。

//check if the row is d datarow
if (e.Row.RowType == DataControlRowType.DataRow)
{
    //cast the row back to a datarowview
    DataRowView row = e.Row.DataItem as DataRowView;

    //cast the sender back to the gridview
    GridView gv = sender as GridView;

    //loop all the columns
    for (int i = 1; i < gv.Columns.Count; i++)
    {
        //compare
        if ((int)row[i] > (int)row[i -1])
        {
            e.Row.Cells[i - 1].ForeColor = Color.Red;
        }
    }
}