Google AdSense display in Asp-GridView

Assuming you have an online forum and to get maximum results from Google AdSense (or any other ad network), you may want to place ads between posts. Here, I will discuss a technique to place ads in pagination-enabled asp:GridView control using c#, as most of the time Asp.Net developers use templated or repeater GridViews to display forum posts.

Ok, there are two ways, you can either bind asp:GridView with a DataSource eg AccessDataSource, SQLDataSource etc, or you have to manually bind it with a DataTable eg. I’m assuming the second case, i.e. the grid is simply bound to a DataTable.

1) Drag a GridView onto the form

2) Add the following properties:
2.a) Allow Paging = “True”
2.b) AutoGenerateColumns=”False”

3) Define event handlers for the following events:
3.a) Row data limit
3.b) Page index change

4) and for the moment just add a single column from asp:TemplateField
5) Since we are binding the GridView with the DataTable, fill the table with the desired data using adapters etc.
6) An exact replica of this table is then created, eg DataTable dt1 = dt.Clone();
7) Import all rows from the first DataTable, eg

foreach(DataRow dr in dt.Rows)
{
dt1.ImportRow(dr);
}

8) What I’m going to do is add a fake row to create space for our ad script. Now suppose you want to place your ad after the first ‘blog post’. Since the ‘page index’ of the first page of the GridView is zero. In the case of the first page, we just insert a fake row at row index one. If the DataTable has a ‘primary key check’, initialize it with -1, say. e.g

DataRow row2 = dt1.NewRow();
row2[“Pk_Col”] = -1; // false value for pk column
dt1.Rows.InsertAt(row2, index);

9) For all other GridView pages (where PageIndex is greater than 0), compute the row indices and insert the dummy rows.

10) Finally, link the temporarily generated table to the grid. e.g

grdContents.DataSource = dt1;
grdContents.DataBind();

11) Now add a WebUserControl file to the website and place the ad script in it. This ad control will load on the dummy rows. In the RowDataBound event handler, if the RowType is DataRow and row2[“Pk_Col”] == -1 then add the AdSense control, eg LoadControl(“AdsControl.ascx”);

That is all.

Leave a comment

Your email address will not be published. Required fields are marked *