Sunday, February 1, 2009

Insert Custom Advertisement Row in GridView

Inserting advertisements between,say every tenth row populated by a gridview


<asp:GridView ID="GridView1" runat="server"  
<asp:BoundField DataField="ProductID" HeaderText="ProductID" />
<asp:BoundField DataField="ProductName" HeaderText="ProductName"/>
<asp:SqlDataSource ID="sdsProducts" runat="server" 
ConnectionString='<%$ ConnectionStrings:NorthwindConnectionString %>'
SelectCommand="SELECT * FROM Products">

protected void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
if (e.Row.DataItem != null)
int intCurrentId = e.Row.RowIndex;
if ((intCurrentId + 1) % 10 == 0)
// Add a row before this record
Table tblGrid = (Table)this.GridView1.Controls[0];
// Get the rowindex of the current row
int intIndex = tblGrid.Rows.GetRowIndex(e.Row);
// Create a new row to hold our subheading
GridViewRow gvrSubHeading = new GridViewRow(intIndex, intIndex, DataControlRowType.Separator, DataControlRowState.Normal);
// Create a table cell for the row
TableCell cellHeader = new TableCell();
// Set the colspan of the cell to the width of the table
cellHeader.ColumnSpan = this.GridView1.Columns.Count;
// Set the text
cellHeader.Text = "Your Advertisement goes here";
// Add the cell to the row
// Add the row to the table
tblGrid.Controls.AddAt(intIndex + 1, gvrSubHeading);


Thats all.

P.S: The DataBase used is Northwind

Courtesy : Samu Zhang - MSFT of
The original VB version posted by Samu Zhang can be found here

Related Posts :

3 comments on "Insert Custom Advertisement Row in GridView"

Add your comment. Please don't spam!
Subscribe in a Reader
Yu-Jin Lim on June 22, 2009 at 1:06 PM said...
This comment has been removed by the author.
Yu-Jin Lim on June 22, 2009 at 1:06 PM said...

Thank you for this interesting code. I was wondering if it is possible to add some google adwords in the first row and the last row of Gridview and I come across your site.

Have you ever tried to insert google adwords and present them as part of the return results?

Legend on February 19, 2013 at 10:46 AM said...

you're a legend mate...I was looking for this all over the internet...and it's so easy to understand as well

Post a Comment