【问题标题】:Color All Empty Cells in ASP.NET GridView为 ASP.NET GridView 中的所有空单元格着色
【发布时间】:2017-01-19 13:49:24
【问题描述】:

我想知道是否有办法将 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;
            }
        }
    }
}

【问题讨论】:

  • OnRowDataBound 事件是您的起点。在那里,您可以遍历所有单元格并检查它们的值。
  • HERE
  • 你能告诉我你是怎么做的吗?
  • 我的单元格没有值。你如何过滤这些?
  • 另外,我不确定我会得到多少列,因为 gridview 是动态的。

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


【解决方案1】:

试试这个:

    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;
        }
    }

【讨论】:

    【解决方案2】:

    您可以为此使用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;
                }
            }
        }
    }
    

    【讨论】:

    • 感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-19
    • 2013-07-31
    • 1970-01-01
    • 2013-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多