Jax
Jax

Reputation: 997

How to change the color of label depending on certain values in the gridview

I have a sqldatasource and gridview.

I have two columns:

ID | Status
1   Closed
2   Opened
3   Waiting

How to change the color of the label in the view state of the gridview depeding on the value from the 'status' column.

For example if the value in the cell is "Closed" the label color will be red , if it's opened then it will become green and so on.

I've thought about looping through all cells of the status column and if the cell contains a certain value the color will change. ( in row data bound event ) . But I haven't done this because I don't find this idea as a good one because of the looping part.

Upvotes: 4

Views: 7182

Answers (3)

Waqar Janjua
Waqar Janjua

Reputation: 6123

You have to write code in the rowdatabound event of your grid view. Example:

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

       }

   }               
}

Upvotes: 1

Pranay Rana
Pranay Rana

Reputation: 176896

You can enable the RowDataBound Event in the markup

<asp:GridView ID="gridview1" runat="server" OnRowDataBound="RowDataBound">

</asp:GridView>

And put this in your Code-Behind file.

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;

   }
}

Upvotes: 2

Nir
Nir

Reputation: 356

use the RowDataBound event from the grid view to check what is the status. You don't need to do a loop because that event (if you register or not) is being called. One thing to note, you will need to make sure you are looking at the right row (header, footer, alternate etc) so something like this

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

Upvotes: 3

Related Questions