Limey
Limey

Reputation: 2772

Apply background color to all labels in a GridView

I have some code that will change the background color of a specific label in a GridView, and that works all well and good.

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

But instead of calling my function for every single label in my Grid (there are a lot, one for every 15 minutes in a day) is there a way to loop through all the contents of the GridView and set the color accordingly?

Upvotes: 3

Views: 622

Answers (4)

SNH
SNH

Reputation: 115

This should do it:

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

            }
        }
    }

Upvotes: 1

Felipe Oriani
Felipe Oriani

Reputation: 38638

Try something like this:

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

Upvotes: 4

Ebad Masood
Ebad Masood

Reputation: 2379

Just traverse in following event and get control, rought like this:

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;


                        }
               }
        }

Upvotes: 0

Andrew Kloos
Andrew Kloos

Reputation: 4608

Here you go...

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

Andrew

Upvotes: 0

Related Questions