问题
I have a datatable that looks like this:
Row1 Row2 Row3 Row4 Row5 Row6
Gold Gold
Pink Pink
#FB7703 #FB7703
Red Red
Yellow
Green
#0B93E1
Purple
This is what the grid looks like when When I bind the datatable to the grid:
How can set background color of the cells in the gridview to the color in the cell?
I know I need to use RowDataBound.
Markup for gridview:
<div>
<asp:GridView ID="GridViewClicks" runat="server"
onrowdatabound="GridViewClicks_RowDataBound">
</asp:GridView>
</div>
And codebehind that fills datatable:
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();
Thanks.
回答1:
You can check the value of each cell in the RowDataBound event and color the cell based on it's value.
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);
}
}
}
}
来源:https://stackoverflow.com/questions/43239923/set-gridview-backcolor-to-color-from-datatable