【问题标题】:How to change the color of label depending on certain values in the gridview如何根据gridview中的某些值更改标签的颜色
【发布时间】:2015-03-21 00:08:08
【问题描述】:

我有一个 sqldatasource 和 gridview。

我有两列:

ID | Status
1   Closed
2   Opened
3   Waiting

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

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

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

【问题讨论】:

    标签: c# asp.net


    【解决方案1】:

    使用网格视图中的 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'
        }
    }
    

    【讨论】:

      【解决方案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 事件中编写代码。 示例:

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

        【讨论】:

          猜你喜欢
          • 2018-12-29
          • 1970-01-01
          • 1970-01-01
          • 2018-07-08
          • 2020-09-16
          • 1970-01-01
          • 2017-03-09
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多