views:

505

answers:

2

I'm maintaining an ASP.Net 2.0 website that displays products in a GridView. The client has asked if I can display an "Add to Cart" button every 10th row. I could do this by putting the button in its own column and flipping the visibility but I wondered if I could inject a new row after every 10 items. This puts the button on a row of its own and doesn't take up column space when it's not visible. Any thoughts on how to do this? TIA

+2  A: 

I don't think there's anyway to do this directly with a GridView (without breaking into the source). But what you could do would be to use some javascript to inject the html for the button into the page's DOM after the GridView is rendered.

You would iterate through all the rows in the table created by the gridview and then after every 10th row, create a new row (with all the cells or a single colspan cell). Inside that cell insert the button with the onClick calling your javascript routine to add the item to the cart.

Keltex
+4  A: 

It is notoriously difficult to insert rows into a GridView. Have you thought about using a Repeater?

Given the following markup:

<asp:Repeater id="repeater" runat="server">
    <ItemTemplate>
     <h1><%#Container.DataItem%></h1>
    </ItemTemplate>
</asp:Repeater>

You could use the following code-behind to insert a custom control after whichever rows you so choose:

using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Generic;

public partial class Default : Page
{
    protected override void OnInit(EventArgs e)
    {
     this.repeater.ItemCreated += repeater_ItemCreated;

     base.OnInit(e);
    }

    protected override void OnLoad(EventArgs e)
    {
     this.repeater.DataSource = new List<String>
     {
      "one", "two", "three", "four", "five", "six", "seven"
     };

     this.repeater.DataBind();

     base.OnLoad(e);
    }

    void repeater_ItemCreated(Object sender, RepeaterItemEventArgs e)
    {
     if (this.repeater.Items.Count > 0
      && this.repeater.Items.Count % 3 == 0)
     {
      this.repeater.Controls.Add(new LiteralControl("<h4>hello world</h4>"));
     }
    }
}
Andrew Hare