单元格值的条件格式

时间:2011-04-18 19:16:21

标签: c# gridview formatting conditional

我一直在研究GridViews的条件格式,但我是ASP.Net的新手并且很难过。这是我发现的对我来说最有意义的代码:

protected void GridviewRowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        int CellValue = Convert.ToInt32(e.Row.Cells[2].Text);
        if (CellValue >= 0)
        {
            e.Row.Cells[2].BackColor = System.Drawing.Color.Green;
        }
        if (CellValue < 0)
        {
            e.Row.Cells[2].BackColor = System.Drawing.Color.Red;
        }
    }
}

GridView非常简单:标题行和三列,标题下有一行,每列中有一个货币金额。我只需要第二行上的数据单元格,如果&gt; = 0则第三列为绿色,如果&lt; 0则为红色。

我在int CellValue =行上得到的格式不正确。

3 个答案:

答案 0 :(得分:3)

尝试将int CellValue =行替换为下面一行

int CellValue = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "Difference"));

价: http://www.johnchapman.name/asp-net-c-change-gridview-cell-background-color-based-on-value/

http://msdn.microsoft.com/en-us/library/4hx47hfe.aspx

答案 1 :(得分:1)

我会使用int.TryParse而不是Convert.ToInt32,并验证您的文本实际上是数字。如果看起来正确,可能的候选者是文本包含空格。

因为你的负数被格式化为($ 1,000.00)。检查字符串是否存在括号,您可以根据

格式化颜色
if (e.Row.Cells[2].Text.Contains(")")) {
  e.Row.Cells[2].BackColor = System.Drawing.Color.Red;
} else {
  e.Row.Cells[2].BackColor = System.Drawing.Color.Green;
}

或更好

e.Row.Cells[2].BackColor = e.Row.Cells[2].Text.Contains(")") ? System.Drawing.Color.Red : System.Drawing.Color.Green;

答案 2 :(得分:0)

您的值中包含无效的字符。去除它们你很高兴

int CellValue = Convert.ToInt32(e.Row.Cells[2].Text.Replace("$","").Replace(",","").Replace(".",""));

可能有更好的方法,但现在就试试

编辑:更新我上面的更改或使用double.Parse()

编辑:

int CellValue = (e.Row.Cells[2].Text.IndexOf('(') > -1) ? 0 : -1;

如果你使用bool

,那就更好了
bool CellValue = e.Row.Cells[2].Text.IndexOf('(') > -1;