如何根据条件更改DataGridview中的列前颜色?

时间:2010-12-28 13:41:51

标签: c# gridview

我有一个像员工一样的表,其中一行是'状态'。 如果状态值为“approve”,那么我想以绿色显示该行 否则我想用红色显示它。 我试过以下但是没有用

if (e.Row.RowType == DataControlRowType.Header)
{ 
    string status = DataBinder.Eval(e.Row.DataItem, "IsApprove").ToString();
    if (status == "pending")
    {
        e.Row.ForeColor = System.Drawing.Color.Red; // Change the row's Text color
    }
}

也是这一个

private void gvleavedetail_cellformatting(object sender, datagridviewcellformattingeventargs e)
{
    // if the column is the artist column, check the
    // value.
    if (this.gvleavedetail.columns[e.columnindex].name == "artist")
    {
        if (e.value != null)
        {
            // check for the string "pink" in the cell.
            string stringvalue = (string)e.value;
            stringvalue = stringvalue.tolower();
            if (stringvalue == "high")
            {
                e.cellstyle.backcolor = color.pink;
            }
        }
    }

但在这种情况下,我收到了datagridviewcellformattingeventargs的错误 我正在使用VS2010

1 个答案:

答案 0 :(得分:3)

大家好我得到了解决方案,这个;)

在RowDataBound事件上写下以下条件代码GRIDVIEW

  protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            string status = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "IsApprove"));

            if (status == "pending")
            {

                e.Row.Cells[7].ForeColor = System.Drawing.Color.Yellow;
            }
            else if(status== "accept")
            {

                e.Row.Cells[7].ForeColor = System.Drawing.Color.Green;
            }
            else if (status == "reject")
            {

                e.Row.Cells[7].ForeColor = System.Drawing.Color.Red;
            }
        }
    }