Displaying Google AdSense in Asp-GridView

0
1

Assuming that you have an online forum and in order to obtain maximum 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 eg AccessDataSource, SQLDataSource etc or you have to bind it manually with a DataTable, say. I am assuming the second case ie 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 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 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. eg

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. eg

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 eg LoadControl ("AdsControl.ascx");

That's all about it.

Source

Leave a Reply