我有这段代码可以在Gridview的某些单元格中设置背景颜色,但是我无法在第一行上使用它。
protected void GrdTask_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
foreach(GridViewRow row in GrdTask.Rows)
{
if (Convert.ToInt32(e.Row.Cells[1].Text) == 0)
{
e.Row.Cells[1].Attributes["Style"] = "background-color: #f20713";
}
if (Convert.ToInt32(e.Row.Cells[1].Text) <= -3)
{
e.Row.Cells[1].Attributes["Style"] = "background-color: #f4d942";
}
if (Convert.ToInt32(e.Row.Cells[1].Text) <= -5)
{
e.Row.Cells[1].Attributes["Style"] = "background-color: #28b779";
}
}
}
对于其余所有行,它工作正常。我在做什么错了?
答案 0 :(得分:1)
您正在循环RowDataBound事件中的行。您不需要这样做,并且会给出错误的结果。每行已调用RowDataBound事件。最好使用DataRowView来获取正确的值并根据该颜色为单元格上色。
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//cast the row back to a datarowview
DataRowView row = e.Row.DataItem as DataRowView;
int cellValue = Convert.ToInt32(row["ColumnName"]);
if (cellValue == 0)
{
e.Row.Cells[1].Attributes["style"] = "background-color: #f20713";
}
else if (cellValue <= -3)
{
e.Row.Cells[1].Attributes["style"] = "background-color: #f4d942";
}
else if (cellValue <= -5)
{
e.Row.Cells[1].Attributes["style"] = "background-color: #28b779";
}
}
}