To read the article online, visit

Creating a Banner Ad System in ASP.NET

By Paul Apostolos


My company has always offered banner advertisements on its Web site, but the advertising sales department asked for more flexibility selling the ads. Specifically, they wanted a weighted banner display system that would allow preferred (more expensive) advertisements to show up more often than those of the more budget-minded advertisers. They also wanted the ability to administer those ads themselves thereby circumventing the occasional doughnut bribes they occasionally offered to me to add a new advertisement to the site right away.

In this article I will step you through the custom ASP.NET ad management application I built for my company. At the end of this article you'll find the complete set of code for the ASP.NET Web pages, User Controls, and necessary stored procedures and database tables. I hope the application I created can be used/extended/enhanced by other ASP.NET developers who need a similar solution.

Step 1: Planning

Before I began, I met with the advertising sales staff to outline the project objectives and features. The advertising department wanted the following seven features:

  1. Allow an unlimited number of banner ads to be displayed on the site
  2. Allow ad placement on specific pages or page categories
  3. Allow the advertising sales department to administer the ads
  4. Ads should have a start date and end date
  5. Allow ads to be deactivated (But preserve their original end date)
  6. Allow ads to be weighted to appear more often than other ads
  7. All ad clicks should be logged and totals should be available to staff

It should also be noted that we currently do not sell ads for specific pages. Instead we offer two categories: home page, and all other pages. However, the banner ad system I created can accommodate more than just two categories. So, if your site has different sections by which ads are sold, you can utilize the ad placement by category to have ads appear only in their respective category.

Step 2: Deciding on the HTML Syntax for Displaying a Banner Ad

Before I wrote any code for the banner ad system, I decided to take a step back, sit down, and conjure up the HTML I'd need to display a random banner ad in an ASP.NET Web page. I'd need two things: a hyperlink tag (<a href="...">...</a>) so that the user could click the banner and be taken to the proper URL, and an <img> tag, showing a random banner (based on the category and weighting of available ads). I deduced that the HTML would look something like:

<a href="TrackAd.aspx?Ad_Id=BannerAdID">
	<img src="BannerAdImageSource"

Step 3: Creating the Database Table to Store Banner Ads

The attribute values in italics would be specific to the current ad being shown. From the objectives list, I assembled a few more required attributes and I designed a table called tbl_NRCA_Banner_Ads that would serve as the store for the banner ads. That is, each banner ad in the system would have a single row in this table. The following screenshot shows this table in SQL Server Enterprise Manager:

A screenshot of the table in SQL Server Enterprise Manager

Note: I used SQL Server 2000 and have included all table generation scripts and stored procedures in the code download available at the end of this article. All stored procedures that are provided will need to have execute permission granted to the Web user. The table tbl_NRCA_Banner_Ads will need select permission granted to the Web user as well.

Step 4: Displaying Banner Ads in a User Control

Next, I decided to create an ASP.NET User Control for displaying the needed HTML. That way, a banner ad could be added to any given Web page by simply adding this User Control where the banner ad should appear. Before we examine the code, realize that I do not use Visual Studio .NET as my development editor, so rather than using the code-behind class technique, I create my ASP.NET Web pages and User Controls with the source code portion in a server-side <script> block. If you plan on integrating my code with your Visual Studio .NET application, you'll want to move the code portion to the VS.NET-created code-behind class file, and the HTML portion in the HTML file...

To begin I imported to proper namespaces required by the control (using the code-behind technique, you'd add these in your code-behind class using Import (VB.NET) or using (C#) statements:

<%@ Control Language="VB" %>
<%@ import Namespace="System.Data" %>
<%@ import Namespace="System.Data.SqlClient" %>

Next, I creating a string property for the User Control, Category. Creating a property for a User Control is as simple as creating a public member variable. (For more information on user controls, be sure to read Scott Mitchell's article An Extensive Examination of User Controls.) This Category property is used by the ASP.NET Web page that contains the User Control to let the User Control know what page (or category) is requesting the banner ad. This is used by the User Control to limit the banner selected to one that belongs to the specified category.

<script runat="server">
   Public Category As String

Before proceeding in to the heart of the Page_Load event handler, I make sure that the Category property has been set. If it has, I declare my database connection, command object and DataReader. I initialize the connection using a connection string from the application's Web.config file. (For information on storing connection strings in the Web.config file be sure to read: Specifying Configuration Settings in Web.config).

Next, I initialize my command object, myCommand, passing it the name of my stored procedure and the database connection. I then set its CommandType attribute to CommandType.StoredProcedure.

   Public Sub Page_Load(sender as Object, e as EventArgs)
     If Len(page) > 0 Then
         Dim myConnection As SqlConnection
         Dim myCommand As SqlCommand
         Dim myDataReader As SqlDataReader
         myConnection = New _
              SqlConnection( ConfigurationSettings.AppSettings("MySQLDSN") )
         myCommand = New SqlCommand("NRCA_sp_Get_Random_Banner", myConnection)
         myCommand.CommandType = CommandType.StoredProcedure

At this point I have my connection and command objects ready to go, but I need to add the value of the Category property to the command's parameters collection so only the appropriate banner is displayed. As we'll see when we examine the NRCA_sp_Get_Random_Banner stored procedure, the stored procedure expects an input parameter indicating the category from which to retrieve the banner.) Adding a parameter is done with the following code:

         Dim parameterPage As New SqlParameter("@Category", SqlDbType.Varchar, 20)
         parameterPage.Value = Category

Now I can open my connection, execute my command, send the output to my DataReader and read the first record.

         myDataReader = myCommand.ExecuteReader()

         If myDataReader.Read() Then

The User Control's HTML portion - as we will see in a moment - contains a HyperLink Web control (hl) and an Image Web control (bannerImg), which will render the HTML hyperlink and <img> tag, as discussed earlier in this article. Therefore, all that is left to do is set the HyperLink and Image Web controls' properties from the DataReader:

            hl.NavigateUrl = "adtracker.aspx?Ad_Id=" & _
            bannerImg.ImageUrl = myDataReader.Item("Image_Src_Path").ToString()
            bannerImg.Height = Unit.Parse(myDataReader.Item("Height"))
            bannerImg.Width = Unit.Parse(myDataReader.Item("Width"))
            bannerImg.AlternateText = myDataReader.Item.Item("Alt_Text")
            bannerImg.BorderStyle = BorderStyle.None

Finally, I close my DataReader and connection objects. If an exception has occurred, the exception information is displayed using Trace.Write(). (Another approach would be to email the system administrator with the exception details.)

         End If

       Catch exp As Exception

       End Try
     End If
   End Sub

<asp:HyperLink runat="server" id="hl">
  <asp:Image runat="server" id="bannerImg"></asp:Image>

In Part 2 of this article, we'll turn from the User Control to the stored procedure. Specifically, we'll examine how the stored procedure NRCA_sp_Get_Random_Banner gets a random banner from a specified category.

  • Read Part 2!

  • Article Information
    Article Title: ASP.NET.Creating a Banner Ad System in ASP.NET
    Article Author: Paul Apostolos
    Published Date: March 31, 2004
    Article URL:

    Copyright 2020 QuinStreet Inc. All Rights Reserved.
    Legal Notices, Licensing, Permissions, Privacy Policy.
    Advertise | Newsletters | E-mail Offers