可重用的方法来更改gridview单元格颜色

时间:2012-01-12 17:23:25

标签: c# asp.net

我需要根据数据值更改gridview单元格的颜色。我可以使用Gridviews RowDataBound事件中的数据行视图和if语句(见下文)轻松完成此操作,但是我需要在30列上执行此操作,如果业务规则发生更改,则需要进行相当长时间的操作。如何将以下内容封装到可以调用的可重用方法中,并传入数据列和单元格索引?

    protected void gv1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.DataItem != null)
        {
            DataRowView drv = (DataRowView)e.Row.DataItem;

            int A = Int32.Parse(drv["A"].ToString());
            if (A <= 74)
            {
                e.Row.Cells[2].BackColor = System.Drawing.Color.Red;
            } 
        }
    }

2 个答案:

答案 0 :(得分:2)

public void SetColor(DataGridViewRow row, string columnName, int cellIndex)
{
    var data = (GridViewRow)row.DataItem;
    int number = Convert.ToInt32(data[columnName]);
    if (number > 74) return;

    row.Cells[cellIndex].BackColor = Color.Red;
}

protected void gv1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType != DataRowType.DataRow) return;
    SetColor(e, "A", 2);
}

答案 1 :(得分:1)

想出来 - 梅克利先生让我走上正轨,我的工作(如果不优雅)解决方案是:

    public void SetColor2(GridViewRow row, string columnName, int cellIndex)
    {
        if (row.RowType == DataControlRowType.DataRow)
        {
            int number = Convert.ToInt32(columnName);
            if (number == 0)
            {
                row.Cells[cellIndex].Text = "";
                return;
            }
            else if ((number > 0) && (number <= 74))
            {
                row.Cells[cellIndex].BackColor = System.Drawing.Color.Red;
                row.Cells[cellIndex].ForeColor = System.Drawing.Color.Black;
                return;
            }
        }
    }

用法:

    protected void gv1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.DataItem != null)
        {
            DataRowView drv = (DataRowView)e.Row.DataItem;
            SetColor2(e.Row, drv["A"].ToString(), 2);
            SetColor2(e.Row, drv["B"].ToString(), 3);
            etc...
        }
    }