Search code examples
c#htmlasp.netrowdatabound

How do I avoid a GridView's Gridlines changing color when applying a class to a cell on the RowDataBound event?


In my website, I have a page with a Gridview that I use to display some data. I capture the RowDataBound event, to find out if certain text is present in a cell. If it is, I color it green, else I color it red.

Here's the problem: the Gridview has horizontal gridlines only. When I change the color of the cell in RowDataBound (I'm actually changing the class), the gridlines take on the color applied. I cannot revert it back, no matter what I try (looping through all cells and setting border-color). Please help.

protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        for (int i = 2; i <= 3; i++)
        {
            if (e.Row.Cells[i].Text.Contains("monkey"))
            {
                e.Row.Cells[i].Attributes.Add("class", "monkey bold");
            }
            else
            {
                e.Row.Cells[i].Attributes.Add("class", "nomonkey bold");
            }
        }
    }

}

The style is as follows:

.monkey
{
    color: #009900;
    border-color: black;
}

.nomonkey
{
    color: red;
    border-color: black;
}

The border-color property seems to have no effect.

The GridView is defined as:

                        <asp:GridView ID="GridView2" runat="server" AllowSorting="False" GridLines="Horizontal" AutoGenerateColumns="false" CellPadding="4" OnRowDataBound="GridView2_RowDataBound" OnDataBound="GridView2_DataBound" CssClass="reportGrid"> 
                        <FooterStyle BackColor="#2F76B8" Font-Bold="True" ForeColor="White" />
                        <HeaderStyle BackColor="#2F76B8" Font-Bold="True" ForeColor="White" />
                        <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
                        <RowStyle BackColor="#FFFFFF" ForeColor="#222222" HorizontalAlign="Center" />

Solution

  • I couldn't find the answer to this anywhere, and couldn't tempt anyone into answering it either, so I worked around it by adding a span inside the cell, and setting its style like so:

                if (e.Row.Cells[i].Text.Contains("monkey"))
                {
                    e.Row.Cells[i].Text = e.Row.Cells[i].Text.Replace("monkey", "<span class=\"monkey\">monkey</span> ");
                }