2012-07-10 33 views
4

我有一個sqldatasource和gridview。如何更改標籤的顏色取決於GridView中的某些值

我有兩列:

ID | Status 
1 Closed 
2 Opened 
3 Waiting 

如何更改標籤的顏色在GridView depeding的視圖狀態從'status'列的值。

例如,如果單元格中的值爲「Closed」,則標籤顏色將變成紅色,如果它是opened則變爲綠色等等。

我曾想過如何遍歷status列的所有單元格,並且如果單元格包含某個值,顏色將會改變。 (在行數據綁定事件中)。但是我沒有這樣做,因爲我不認爲這個想法是一個好主意,因爲它是循環的部分。

回答

2

您可以在標記使RowDataBound事件

<asp:GridView ID="gridview1" runat="server" OnRowDataBound="RowDataBound"> 

</asp:GridView> 

並把它放在你的代碼隱藏文件中。

protected void RowDataBound(Object sender, GridViewRowEventArgs e) 
    { 
    if(e.Row.RowType == DataControlRowType.DataRow) 
    { 
     // Retrieve the underlying data item. In this example 
     // the underlying data item is a DataRowView object. 
     DataRowView rowView = (DataRowView)e.Row.DataItem; 

     // Retrieve the state value for the current row. 
     String state = rowView["state"].ToString(); 

     //format color of the as below 
     if(state == "Closed") 
       (e.Row.FindControl("lbl1") as Label).BackColor = Color.Red; 

     if(state == "Open") 
       (e.Row.FindControl("lbl1") as Label).BackColor = Color.Green; 

     if(state == "Waiting") 
       (e.Row.FindControl("lbl1") as Label).BackColor = Color.Yellow; 

    } 
} 
3

使用網格視圖中的RowDataBound事件來檢查什麼是狀態。你不需要做一個循環,因爲這個事件(如果你註冊或者不被註冊)正在被調用。 有一點要注意,你需要確保你正在尋找正確的行(頁眉,頁腳,備用等),所以像這樣

void YourGridViewName_RowDataBound(Object sender, GridViewRowEventArgs e) 
{ 

    if(e.Row.RowType == DataControlRowType.DataRow) 
    { 
     // Do your color change here by accessing the col with e.Row.Cells[column_index].BackColor = 'what ever you want' 
    } 
} 
1

您必須在網格視圖的rowdatabound事件中編寫代碼。例如:

private GridView1_RowDatabound(object sender,EventArgs e) 
{ 
    if(e.Row.RowType == DataControlRowType.DataRow) 
    { 
    // You have to put your logic here. 
     if(e.Row.Cells[1].Text == "closed") 
     { 
      // to get a reference to label control 
      Label lb = e.Row.FindControl("LabelCOntrolID"); 

     } 

    }    
}