在ASP.NET GridView中为所有空单元格着色

时间:2017-01-19 13:49:25

标签: c# asp.net .net gridview cells

我想知道是否有办法为GridView中的所有空单元格着色为橙色。我的GridView中的列是动态生成的。任何帮助表示赞赏。

谢谢!

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    //check if the rowtype is a datarow
    if (e.Row.RowType == DataControlRowType.DataRow)
    {


        //loop all the cells in the row
        for (int i = 0; i < e.Row.Cells.Count; i++)
        {
            int value = 0;

            //try converting the cell value to an int
            try
            {
                value = Convert.ToInt32(e.Row.Cells[i].Text);
            }
            catch
            {
            }

            //check the value and set the background color
            if (value == "")
            {
                e.Row.Cells[i].BackColor = Color.Green;
            }
            else 
            {
                e.Row.Cells[i].BackColor = Color.White;
            }
        }
    }
}

2 个答案:

答案 0 :(得分:3)

试试这个:

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        for (int i = 0; i < e.Row.Cells.Count; i++)
        {
            if (e.Row.Cells[i].Text == "&nbsp;")
                e.Row.Cells[i].BackColor = Color.Orange;
        }
    }

enter image description here

答案 1 :(得分:1)

您可以使用RowDataBound事件,就像您现在所做的那样。但有一个问题。您创建了int value,但之后尝试将value与字符串if (value == "")进行比较。这是行不通的。

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

        //loop all columns in the row
        for (int i = 0; i < e.Row.Cells.Count; i++)
        {
            //check if the string is null of empty in the source data
            //(row[i]) instead of e.Row.Cells[i].Text
            if (string.IsNullOrEmpty(row[i].ToString()))
            {
                e.Row.Cells[i].BackColor = Color.Green;
            }
            else
            {
                e.Row.Cells[i].BackColor = Color.White;
            }
        }
    }
}