How to change label color based on specific values ​​in gridview

I have sqldatasource and gridview.

I have two columns:

ID | Status 1 Closed 2 Opened 3 Waiting 

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

For example, if the value in the cell is " Closed ", the color of the label will be red; if it is opened , then it will turn green, etc.

I thought about iterating over all the cells in the status column, and if the cell contains a specific value, the color will change. (in the event associated with the row data). But I didn’t do it, because I don’t think this idea is good, because it goes in cycles.

+4
source share
3 answers

You can enable the RowDataBound event in the markup

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

And put this in a 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; } } 
+2
source

use the RowDataBound event from the grid view to check what the status is. You do not need to do a loop because this event (if you register or not) is called. It should be noted that you need to make sure that you are looking at the correct line (header, footer, alternating, 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' } } 
+3
source

You need 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"); } } } 
+1
source

All Articles