2012-07-02 62 views
3

我有一些代码可以更改GridView中特定标签的背景颜色,并且工作得很好。将背景颜色应用于GridView中的所有标签

protected void HighLight_Hours(Label Quarter) 
{ 
    Int32 Hours; 
    Int32.TryParse(Quarter.Text, out Hours); 
    switch (Hours) 
    { 
     case 0: 
      Quarter.BackColor = Color.Red; 
      break; 
     case 1: 
      Quarter.BackColor = Color.Yellow; 
      break; 
     case 2: 
      Quarter.BackColor = Color.LightGreen; 
      break; 
    } 
} 

但不要叫我为每一个标签的功能在我的网格(也有很多,一个在天,每15分钟)有通过GridView和组的所有内容的方式来循环颜色相应?

+1

你使用的是GridView吗?如果是这样,这听起来像你可能想在[RowDataBound'](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowdatabound.aspx)事件。 – jadarnel27

+0

@ jadarnel27:这是我目前正在做的事情,但我必须按名称引用每个标签。 – Limey

+0

每行只有一个标签吗?你为什么不想按名称指定标签?如果沿着这条路走,你会在每一行添加另一个标签,然后你会遇到问题。 – SNH

回答

1

This s应该这样做:

protected void gv_OnRowDataBound(object sender, GridViewRowEventArgs e) 
    { 
     if (e.Row.RowType == DataControlRowType.DataRow) 
     { 

      foreach (DataControlFieldCell dcfc in e.Row.Controls) 
      { 
       DataControlFieldCell dataControlFieldCell = dcfc; 

       foreach(var control in dataControlFieldCell.Controls) 
        if (control is Label) 
         HighLight_Hours((Label) control); 

      } 
     } 
    } 
0

在这里你去...

foreach (DataGridItem CurrentItem in SomeKindOfDataGrid.Items) 
    CurrentItem.BackColor = Color.Red; 

安德鲁

+1

OP正在使用'GridView',而不是'DataGrid'。你几岁;-) – jadarnel27

+0

什么是DataGrid? – SNH

+0

@Saied自从ASP.NET 2.0以来,GridView就一直存在。所以我猜想DataGrid会在2004/2005之前。 – jadarnel27

0

只是遍历以下事件,并得到控制,这样rought:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) 
     { 
      foreach (GridViewRow gvr in GridView1.Rows) 
       { 
         foreach (Control ctrl in gvr.Controls) 
        { 

          Label lbl = (Label)e.Row.FindControl("yourlabel"); 
          lbl.ForeColor =system.drawing.color.red; 


         } 
       } 
     } 
+0

他希望在不知道名称的情况下得到标签,但只有在每行有一个标签时才能使用,所以此解决方案目前为止还不错。 – SNH

4

尝试是这样的:

protected void gv_RowDataBound(object sender, GridViewRowEventArgs e) 
{ 
    if (e.Row.RowType == DataControlRowType.DataRow) 
    { 
     // read in all controls of a row 
     foreach (var control in e.Row.Controls) 
     { 
      // check if the control is a label 
      if (control is Label) 
      { 
       // call your function and cast the control to a Label 
       HighLight_Hours((Label) control); 
      } 
     } 
    } 
} 
+0

这取决于每行只有一个标签。 – SNH

+0

但是foreach循环没有处理这个问题吗?该解决方案应该允许他的代码检查每个控件,并为解决标签的每个控件调用高亮功能。 – Marshall

+0

@马歇尔 - 是的,但是这是行中的所有标签还是只是一个特定的标签? – SNH