Jump to content
Xtreme .Net Talk

Coloring the cell of a GridView based on Condition [VS 2008 - ASP.NET/C#]


Recommended Posts

Posted

I am trying to find a way to display certain cells in RED or YELLOW based on specific criteria, ideally the cell itself could change color (it has to be very apparant) but in the worst-case a method of simply changing the color of the text would do - if there is no way to change the cell color.

 

Specifically, I have a DataSet with a table like the following:

[Date]-------[Type]--[Value]

11/20/2008---HEP-----10.1

11/20/2008---HAP-----7.8

11/21/2008---HEP-----12

11/21/2008---HAP-----100

11/21/2008---AAH-----2

(as an example)

 

Currently I get the DataSet (SQL table) and then set it as a datasource to my GridView on my ASP.NET web page - this works great.

 

Now I need to make the following changes:

- If [VALUE] is greater then 99 set the cell in question RED

- If [VALUE] is less then 10 set the cell in question YELLOW

 

I've got absolutly no clue how to accomplish this...

Is GridView the best method of displaying the data and setting colors? Is there an easy way to iterate over the data and determine which should be what color, is there a simpler approach?

 

Any help would be greatly appreciated.

Thanks,

Posted (edited)

Something like this will help you:

 

(assumes that your value is a string, you can change to the correct data type (int, double, etc))

// you will need to hookup the  RowDataBound event in aspx to this code behind method
protected void dgvTasks_RowDataBound(Object sender, GridViewRowEventArgs e)
       {
           try
           {
               if (e.Row.RowType == DataControlRowType.DataRow)
               {
                   GridViewRow gr = (GridViewRow)e.Row;
                   switch (DataBinder.Eval(gr.DataItem, "Value").ToString())
                   {
                        case "10":
                           gr.Attributes.Add("class", "gridYellow");
                           break;
                   }
               }
           }
           catch (Exception ex)
           {
               // handle error
           }
       }

 

Then in your stylesheet you need to setup a CSS Class called "gridYellow".

 

HTH

Edited by Nate Bross

~Nate�

___________________________________________

Please use the [vb]/[cs] tags on posted code.

Please post solutions you find somewhere else.

Follow me on Twitter here.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...