将gridview backcolor设置为数据表中的颜色?

时间:2017-04-05 19:23:27

标签: c# css asp.net gridview datatable

我的datatable看起来像这样:

Row1       Row2    Row3    Row4    Row5    Row6
Gold       Gold              
Pink       Pink              
#FB7703    #FB7703               
Red        Red               
Yellow                       
Green                        
#0B93E1                      
Purple                       

当我将数据表绑定到网格时,这就是网格的样子: enter image description here

如何将gridview中单元格的背景颜色设置为单元格中的颜色?

我知道我需要使用RowDataBound

gridview的标记:

<div>
    <asp:GridView ID="GridViewClicks" runat="server" 
        onrowdatabound="GridViewClicks_RowDataBound">
    </asp:GridView>
</div>

填充数据表的代码隐藏:

DataTable dataTable = GetColors();

DataTable gridTable = new DataTable();
gridTable.Columns.Add("Row1", typeof(string));
gridTable.Columns.Add("Row2", typeof(string));
gridTable.Columns.Add("Row3", typeof(string));
gridTable.Columns.Add("Row4", typeof(string));
gridTable.Columns.Add("Row5", typeof(string));
gridTable.Columns.Add("Row6", typeof(string));

for (int i = 0; i < 8; i++)
{
    var r = gridTable.NewRow();
    gridTable.Rows.Add(r);
}

foreach (DataRow r in dataTable.Rows)
{
    int rowNum = Convert.ToInt16(r[1]) - 1;
    int colNum = Convert.ToInt16(r[3]);
    gridTable.Rows[rowNum][colNum] = r["color"].ToString();
}

GridViewClicks.DataSource = gridTable;
GridViewClicks.DataBind();

感谢。

1 个答案:

答案 0 :(得分:1)

您可以检查RowDataBound事件中每个单元格的值,并根据单元格的值为单元格着色。

protected void GridViewClicks_RowDataBound(object sender, GridViewRowEventArgs e)
{
    //check if the current row is a datarow
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        //loop all the cells in the row
        foreach (TableCell cell in e.Row.Cells)
        {
            //check if the color is hex or a string
            if (cell.Text.Contains("#"))
            {
                cell.BackColor = ColorTranslator.FromHtml(cell.Text);
            }
            else
            {
                cell.BackColor = Color.FromName(cell.Text);
            }
        }
    }
}