4

我有一个 sqldatasource 和 gridview。

我有两列:

ID | Status
1   Closed
2   Opened
3   Waiting

如何根据'status'列中的值更改网格视图的视图状态中标签的颜色。

例如,如果单元格中的值为“ Closed”,则标签颜色将为红色,如果是,opened则它将变为绿色,依此类推。

我考虑过遍历status列的所有单元格,如果单元格包含某个值,颜色会改变。(在行数据绑定事件中)。但我没有这样做,因为我不认为这个想法是一个好的想法,因为循环部分。

4

3 回答 3

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'
    }
}
于 2012-07-10T19:55:59.930 回答
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;

   }
}
于 2012-07-10T19:56:45.063 回答
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");

       }

   }               
}
于 2012-07-10T19:56:49.753 回答