2012-07-10 40 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"); 

     } 

    }    
}