2017-04-05 117 views
-1

我有一個datatable,看起來像這樣:將gridview背景顏色設置爲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(); 

感謝。

+0

請讓我知道爲什麼我的問題是downvoted,以便我可以改善它。 – rbhat

回答

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