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



如果我有一个 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");
}
}

您需要比较源数据中的值,而不是单元格。请注意,gv.Columns.Count仅适用于模板字段和绑定字段,不适用于自动生成的列。

//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;
}
}
}

最新更新