如何根据Emp_sal列值在gridview中设置行颜色

时间:2013-09-25 13:06:39

标签: asp.net gridview

if (e.Row.RowType == DataControlRowType.DataRow)
    {
        int esal = int.Parse(e.Row.Cells[3].Text.ToString());
        if (esal > 12000)
        {
            e.Row.ForeColor = System.Drawing.Color.Blue;
            e.Row.BackColor = System.Drawing.Color.LightPink;
            e.Row.Font.Italic = true;
        }
        else if (esal == 15000)
        {
            e.Row.ForeColor = System.Drawing.Color.Brown;
            e.Row.BackColor = System.Drawing.Color.LightBlue;
            e.Row.Font.Italic = true;
        }
        else
        {
            e.Row.ForeColor = System.Drawing.Color.White;
            e.Row.BackColor = System.Drawing.Color.LightGreen;
            e.Row.Font.Italic = true;
        }

    }

我试过这个,但是我得到了一个例外,比如输入字符串的格式不正确..请帮助我......

2 个答案:

答案 0 :(得分:1)

if (e.Row.RowType == DataControlRowType.DataRow)
{
if (!string.IsNullOrEmpty(e.Row.Cells[3].Text))
{

    int esal = int.Parse(e.Row.Cells[3].Text.ToString());
    if (esal > 12000)
    {
        e.Row.ForeColor = System.Drawing.Color.Blue;
        e.Row.BackColor = System.Drawing.Color.LightPink;
        e.Row.Font.Italic = true;
    }
    else if (esal == 15000)
    {
        e.Row.ForeColor = System.Drawing.Color.Brown;
        e.Row.BackColor = System.Drawing.Color.LightBlue;
        e.Row.Font.Italic = true;
    }
    else
    {
        e.Row.ForeColor = System.Drawing.Color.White;
        e.Row.BackColor = System.Drawing.Color.LightGreen;
        e.Row.Font.Italic = true;
    }
}
}

答案 1 :(得分:1)

试试这个

if (e.Row.RowType == DataControlRowType.DataRow)
{
    int esal = -1;
    if(int.TryParse(e.Row.Cells[3].Text.ToString(),out esal))
    {
        if (esal > 12000)
        {
            e.Row.ForeColor = System.Drawing.Color.Blue;
            e.Row.BackColor = System.Drawing.Color.LightPink;
            e.Row.Font.Italic = true;
        }
        else if (esal == 15000)
        {
            e.Row.ForeColor = System.Drawing.Color.Brown;
            e.Row.BackColor = System.Drawing.Color.LightBlue;
            e.Row.Font.Italic = true;
        }
        else
        {
            e.Row.ForeColor = System.Drawing.Color.White;
            e.Row.BackColor = System.Drawing.Color.LightGreen;
            e.Row.Font.Italic = true;
        }
    }
    else
    {
         //show message the that e.Row.Cells[3].Text.ToString() doesn't contain integer.
    }
}