2010-06-30 88 views
3

好吧,我顯然沒有喂谷歌正確的查詢,或者我現在已經發現了。我希望這個論壇上有人能幫助我。如何根據條件語句更改gridview單元格的背景顏色?

所以我有一個數據表,我添加行到基於datareader從數據庫上執行的sql查詢獲取其信息。到現在爲止還挺好。現在,其中一列稱爲「分析」,如果前兩列匹配,我需要其背景顏色爲綠色,否則爲紅色。

如果我不能觸摸背景顏色,我想插入一個特殊字符,任何不被解釋爲文本的javascript。

簡而言之,我想要從代碼隱藏的CSS視圖的CSS控制。我看了看,無濟於事。我發現this的傢伙,但我沒有檢查他的解決方案是否可以在ASP.Net/C#網站上使用。有任何想法嗎?

回答

3

GridView_RowDataBound事件中,獲取要更改背景色的單元格,設置單元格的顏色(如果條件測試爲true)。

/// <summary> 
/// Handles gridview row data bound event. 
/// </summary> 
/// <param name="sender">Sender Object</param> 
/// <param name="e">Event Argument</param> 
protected void Gv_RowDataBound(object sender, GridViewRowEventArgs e) 
{ 
    // We don’t want to apply this to headers. 
    if (e.Row.RowType == DataControlRowType.DataRow) 
    { 
     try 
     { 
      //your data-object that is rendered in this row, if at all required. 
      //Object obj = e.Row.DataItem; 

      //find the right color from condition 
      string color = condition ? "#ff9900" : "some-other-color"; 

      //set the backcolor of the cell based on the condition 
      e.Row.Cells[4].Attributes.Add("Style", "background-color: " + color + ";"); 
     } 
     catch 
     { 
     } 
    } 
} 
+0

這工作!非常感謝你:) – Freakishly 2010-07-01 01:31:08

0
protected void GVKeywordReport_RowDataBound(object sender, GridViewRowEventArgs e) 
     { 

      if (e.Row.RowType == DataControlRowType.DataRow) 
      { 
       DataRow pr = ((DataRowView)e.Row.DataItem).Row; 
       int oldPos = Convert.ToInt32(pr["oldposition"]); 
       int newPos = Convert.ToInt32(pr["newposition"]); 
       GVKeywordReport.HeaderRow.Cells[3].Text = txtfrmdate.Text; 
       GVKeywordReport.HeaderRow.Cells[4].Text = txtEndDate.Text; 

       GVKeywordReport.HeaderRow.BackColor = ColorTranslator.FromHtml("#B3B300"); 
       e.Row.Cells[0].BackColor = ColorTranslator.FromHtml("#B3B300"); 
       e.Row.Cells[5].BackColor = ColorTranslator.FromHtml("#FFFFFF"); 

       if (oldPos == newPos) 
       { 
        e.Row.BackColor = ColorTranslator.FromHtml("#FF950E"); 
        e.Row.Cells[6].Text = "No Change"; 
       } 
       else if (oldPos > newPos) 
       { 
        e.Row.BackColor = ColorTranslator.FromHtml("#FFFFCC"); 
        e.Row.Cells[6].Text = "Improved"; 
       } 
       else 

       { 
        e.Row.BackColor = ColorTranslator.FromHtml("#FF0000"); 
        e.Row.Cells[6].Text = "Decreased"; 
       } 
       // e.Row.Cells[0].BackColor = ColorTranslator.FromHtml("#7DA647"); 
      } 
     } 
+0

雖然這個代碼塊可能會回答這個問題,但最好能提供一些解釋爲什麼它會這樣做 – 2015-01-27 08:42:16

相關問題