mynameisneo
mynameisneo

Reputation: 483

Display alternate row color in data grid

Could someone help with a quick alternate way to jquery to display alternate rows with different background colors? Trying with a foreach loop but not having much luck. Many thanks!!!

    <div class="acgridhdrstart">Account Name</div>
<div class="acgridhdr">Account Region</div>
<div class="acgridhdr">Account Representative</div>
<div class="acgridhdr">Peer Partner</div>
<div class="acgridhdr">Last Updated</div>
@while (myreader.Read())
{
<div class="bgcol">
 <span class="acgridstart">@myreader["acname"]</span>
 <span class="acgrid">@myreader["acregion"]</span>
 <span class="acgrid">@myreader["acrep"]</span>
 <span class="acgrid">@myreader["acpeer"]</span>
 <span class="acgrid">@myreader["lastupdated"]</span>
</div>
}

Upvotes: 1

Views: 1341

Answers (4)

jgauffin
jgauffin

Reputation: 101150

Like this:

<script type="text/javascript">
    $(function() {
        $('#yourtable tr:odd').css('background-color', '#cccccc');
    });
</script>

Upvotes: 1

mynameisneo
mynameisneo

Reputation: 483

I ended up using SQLDataAdapter and returned the data as follows:

@for (int i = 0; i < dt.Rows.Count; i++)
{
    string rowclass = "bgcol";
    if (i % 2 == 0)
    {
        rowclass = "bgalt";
        }
        else
        {
            rowclass = "bgcol";
        }   
<div class="@rowclass">
 <span class="acgridstart">@dt.Rows[i]["acname"].ToString()</span>
 <span class="acgrid">@dt.Rows[i]["acregion"].ToString()</span>
 <span class="acgrid">@dt.Rows[i]["acrep"].ToString()</span>
 <span class="acgrid">@dt.Rows[i]["acpeer"].ToString()</span>
 <span class="acgrid">@dt.Rows[i]["lastupdated"].ToString()</span>
</div>
}

Upvotes: 0

James Manning
James Manning

Reputation: 13579

With CSS3 you can :nth-child(even) and :nth-child(odd)

http://www.w3.org/TR/css3-selectors/#nth-child-pseudo

jQuery version, FWIW:

http://api.jquery.com/nth-child-selector/

If you want it in the view code, Phil Haack's Cycle method might be useful

http://haacked.com/archive/2008/08/07/aspnetmvc_cycle.aspx

On the off chance you don't know about it, WebGrid has rowStyle and alternatingRowStyle

http://msdn.microsoft.com/en-us/magazine/hh288075.aspx

http://msdn.microsoft.com/en-us/library/system.web.helpers.webgrid.gethtml(v=vs.99).aspx

Upvotes: 5

Jimmy Miller
Jimmy Miller

Reputation: 1319

If you can write each rows markup with either an "even" or "odd" class then you can use CSS easily to achieve this effect. Otherwise, you'll need to use something like jQuery to add the appropriate "even" and "odd" class that correspond to your stripe styles.

Upvotes: 1

Related Questions