How can I change the background color of a gridview cell, based on a conditional statement?

馋奶兔 提交于 2019-12-06 02:00:39

In the GridView_RowDataBound event, get the cell you want to change the back-color, set the color of the cell if your condition is tested true.

/// <summary>
/// Handles gridview row data bound event.
/// </summary>
/// <param name="sender">Sender Object</param>
/// <param name="e">Event Argument</param>
protected void Gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
    // We don’t want to apply this to headers.
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        try
        {
            //your data-object that is rendered in this row, if at all required.
            //Object obj = e.Row.DataItem;

            //find the right color from condition
            string color = condition ? "#ff9900" : "some-other-color";

            //set the backcolor of the cell based on the condition
            e.Row.Cells[4].Attributes.Add("Style", "background-color: " + color + ";");
        }
        catch
        {
        }
    }
}
 protected void GVKeywordReport_RowDataBound(object sender, GridViewRowEventArgs e)
        {

            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                DataRow pr = ((DataRowView)e.Row.DataItem).Row;
                int oldPos = Convert.ToInt32(pr["oldposition"]);
                int newPos = Convert.ToInt32(pr["newposition"]);
                GVKeywordReport.HeaderRow.Cells[3].Text = txtfrmdate.Text;
                GVKeywordReport.HeaderRow.Cells[4].Text = txtEndDate.Text;

                GVKeywordReport.HeaderRow.BackColor = ColorTranslator.FromHtml("#B3B300");
                e.Row.Cells[0].BackColor = ColorTranslator.FromHtml("#B3B300");
                e.Row.Cells[5].BackColor = ColorTranslator.FromHtml("#FFFFFF");

                if (oldPos == newPos)
                {
                    e.Row.BackColor = ColorTranslator.FromHtml("#FF950E");
                    e.Row.Cells[6].Text = "No Change";
                }
                else if (oldPos > newPos)
                {
                    e.Row.BackColor = ColorTranslator.FromHtml("#FFFFCC");
                    e.Row.Cells[6].Text = "Improved";
                }
                else  

                {
                    e.Row.BackColor = ColorTranslator.FromHtml("#FF0000");
                    e.Row.Cells[6].Text = "Decreased";
                }
               // e.Row.Cells[0].BackColor = ColorTranslator.FromHtml("#7DA647");
            }
        }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!