根据条件更改gridview行文本颜色

时间:2018-01-10 13:48:16

标签: c# asp.net .net c#-4.0 gridview

我正在动态填充gridview,如果值为<=0,我需要将forecolor设置为红色。如果我的网格是静态的,我可以使用下面的代码,因为我的网格是动态的,我如何检查单元格值中的数字以改变前景色。

我需要检查每个单元格值是否为<=0,然后将forecolor设置为红色。

代码:

对于静态网格

if (e.Row.RowType == DataControlRowType.DataRow)
{
    e.Row.Cells[3].ForeColor = System.Drawing.Color.Red;
}

我也尝试了下面的代码,但它没有用。

if (e.Row.RowType == DataControlRowType.DataRow)
{
    for (int i = 0; i < GridView1.Rows.Count; i++)
    {
        TableCell cell = e.Row.Cells[i];
        int quantity = int.Parse(cell.Text);
        if (quantity == 0)
        {
            cell.ForeColor = Color.Red;
        }
    }
}

请提供有关如何实现这一目标的建议或意见。

更新1:

我已经更新了我的代码,但仍然无法获得所需的颜色。

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        foreach (GridViewRow row in GridView1.Rows)
            {
                for (int i = 0; i < GridView1.Columns.Count; i++)
                {
                    TableCell cell = row.Cells[i];
                    int quantity = int.Parse(cell.Text);
                    if (quantity <= 0)
                    {
                        cell.ForeColor = Color.Red;
                    }
                }
            }

        if (e.Row.RowType == DataControlRowType.Header)
            {

            }

        if (e.Row.RowType == DataControlRowType.DataRow)
            {                    

            }
    }

1 个答案:

答案 0 :(得分:1)

我认为这是最好的方式

foreach(GridViewRow row in YourGridViewID.Rows)
{
    for(int i = 0; i < YourGridViewID.Columns.Count; i++)
    {
               TableCell cell = row.Cells[i];
                int quantity = int.Parse(cell.Text);
                if (quantity <= 0)
                {
                    cell.ForeColor = Color.Red;
                } 
    }
}