3

我有一些代码可以更改 a 中特定标签的背景颜色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;
    }
}

但是,不是为我的 Grid 中的每个标签调用我的函数(有很多,一天每 15 分钟一个),有没有办法循环遍历所有内容GridView并相应地设置颜色?

4

4 回答 4

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);
            }
        }
    }
}
于 2012-07-02T19:10:11.157 回答
1

这应该这样做:

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

            }
        }
    }
于 2012-07-02T20:04:12.970 回答
0

干得好...

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

安德鲁

于 2012-07-02T19:07:15.223 回答
0

只需遍历以下事件并获得控制权,如下所示:

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;


                        }
               }
        }
于 2012-07-02T19:08:55.743 回答