Displaying Google AdSense in Asp-GridView

Posted on

Assuming that you have an online forum and in order to obtain max results from Google AdSense (or any other ad network), you might want to place ads in between the posts. Here, I will discuss a technique to place ads in paging enabled asp:GridView control using c# as most of the times Asp.Net developers use Templated GridViews or Repeaters to display forum posts.

Ok, there are two ways: either you can bind asp:GridView with a DataSource e.g. AccessDataSource, SQLDataSource etc or you have to bind it manually with a DataTable, say. I am 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) AllowPaging=”True”

2.b) AutoGenerateColumns=”False”

3) Define event handlers for the following evetns:

3.a) RowDataBound

3.b) PageIndexChanging

4) and for the time being just add a single column of asp:TemplateField

5) As we are binding GridView with DataTable so fill in the table with desired data using adapters etc.

6) Then an exact replica of this table is created e.g. DataTable dt1 = dt.Clone();

7) Import all rows from the first DataTable e.g.

foreach (DataRow dr in dt.Rows)

{

dt1.ImportRow(dr);

}

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

DataRow row2 = dt1.NewRow();

row2[“Pk_Col”] = -1; // fake value for pk column

dt1.Rows.InsertAt(row2, index);

9) For all other GridView pages (where PageIndex is greater than 0) calculate the row indexes and insert the fake rows.

10) Finally bind the temporarily generated table with the grid. e.g.

grdContents.DataSource = dt1;

grdContents.DataBind();

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

That’s all about it.

Leave a Reply

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