Gridview.RowdataBound在第一行上不起作用 [英] Gridview.RowdataBound not working on first row

查看:69
本文介绍了Gridview.RowdataBound在第一行上不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码可以在Gridview的某些单元格中设置背景颜色,但是我无法在第一行中使用它.

I have this code for setting Background color in some cells in a Gridview, but i can't get it to work on the first row.

protected void GrdTask_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        foreach(GridViewRow row in GrdTask.Rows)
        {
            if (Convert.ToInt32(e.Row.Cells[1].Text) == 0)
            {                   
                e.Row.Cells[1].Attributes["Style"] = "background-color: #f20713";
            }               
            if (Convert.ToInt32(e.Row.Cells[1].Text) <= -3)
            {
                e.Row.Cells[1].Attributes["Style"] = "background-color: #f4d942";
            }
            if (Convert.ToInt32(e.Row.Cells[1].Text) <= -5)
            {
                e.Row.Cells[1].Attributes["Style"] = "background-color: #28b779";
            }
        }          
    }

对于其余所有行,它都可以正常工作.我在做什么错了?

For all the rest of the rows it works fine. What am i doing wrong?

推荐答案

您正在循环RowDataBound事件中的行.您不需要这样做,并且会给出错误的结果.每行已调用RowDataBound事件.最好使用DataRowView来获取正确的值并根据该值为单元格上色.

You're looping the rows in the RowDataBound event. you don't need to do that and will give incorrect results. The RowDataBound event is already called per row. Better use the DataRowView to get the correct value and color the cell based on that.

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        //cast the row back to a datarowview
        DataRowView row = e.Row.DataItem as DataRowView;

        int cellValue = Convert.ToInt32(row["ColumnName"]);

        if (cellValue == 0)
        {
            e.Row.Cells[1].Attributes["style"] = "background-color: #f20713";
        }
        else if (cellValue <= -3)
        {
            e.Row.Cells[1].Attributes["style"] = "background-color: #f4d942";
        }
        else if (cellValue <= -5)
        {
            e.Row.Cells[1].Attributes["style"] = "background-color: #28b779";
        }
    }
}

这篇关于Gridview.RowdataBound在第一行上不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆