Applying styles to a GridView matching certain criteria

Posted by NickK on Stack Overflow See other posts from Stack Overflow or by NickK
Published on 2010-12-26T11:11:47Z Indexed on 2010/12/26 13:54 UTC
Read the original article Hit count: 225

Filed under:
|

Hi everyone.

I'm fairly new to ASP.Net so it's probably just me being a bit stupid, but I just can't figure out why this isn't working.

Basically, I have a GridView control (GridView1) on a page which is reading from a database. I already have a CSS style applied to the GridView and all I want to do is change the background image applied in the style depending on if a certain cell has data in it or not.

The way I'm trying to handle this change is updating the CSS class applied to each row through C#. I have the code below doing this:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    GridViewRow row = e.Row;
    string s = row.Cells[7].Text;

    if (s.Length > 0)
    {
        row.CssClass = "newRowBackground";
    }
    else
    {
        row.CssClass = "oldRowBackground";
    }
}

In theory, the data from Cell[7] will either be null or be a string (in this case, likely a person's name).

The problem is that when the page loads, every row in the GridView has the new style applied to it, whether it's empty or not. However, when I change it to use hard coded examples, it works fine. So for example, the below would work exactly how I want it to:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    GridViewRow row = e.Row;
    string s = row.Cells[7].Text;

    if (s == "Smith") //Matching a name in one of the rows
    {
        row.CssClass = "newRowBackground";
    }
    else
    {
        row.CssClass = "oldRowBackground";
    }
}

It seems as if the top piece of code is always returning the string with a value greater than 0, but when I check the database the fields are all null (except for my test record of "Smith").

I'm probably doing something very simple that's wrong here, but I can't see what. Like I said, I'm still very new to this. One thing I have tried is changing the argument in the if statement to things like: if (s != null), if (s != "") and if (s == string.empty) all with no luck.

Any help is greatly appreciated and don't hesitate to tell me if I'm just being stupid here. :)

© Stack Overflow or respective owner

Related posts about c#

Related posts about ASP.NET