Click here to Skip to main content
12,829,850 members (44,177 online)
Click here to Skip to main content
Add your own
alternative version


58 bookmarked
Posted 10 Aug 2003

Object-Oriented ASP.NET

, 10 Aug 2003
Rate this:
Please Sign up or sign in to vote.
Use the powerful object-oriented features of C# and VB.NET to build re-usable classes in ASP.NET
<!------------------------------- STEP 3 ---------------------------><!-- Add the article text. Please use simple formatting (


etc) -->


ASP.NET brings a whole new world of functionality, power, and ease of rapid development for web programmers. Some of these features, such as the advent of code-behind, are well documented and have become standard practice in everyday development. Another feature ASP.NET brings us is development with a real, compiled language. We can now leverage the object-oriented aspects of these new languages and put them to work in our code. We can take advantage of inheritance, polymorphism, and encapsulation when writing web apps while still maintaining an Microsoft DNA-style n-tier architecture.

I'm not going to try to explain these OO design concepts because they are already the subject of a great many articles (and books). For example, you could try this article right here on CP for an introduction.

I will be showing a simple example of how you can use inheritance and encapsulation in ASP.NET. I will show how you can customize a datagrid by encapsulating some behavior in a subclass of the datagrid, and thereby making the derived DataGrid class re-usable across multiple forms or applications. I'll be using C# for this example, but the same principles apply to VB.NET.

A Real-World Example

For this example I will be using a common scenario developers encounter with the DataGrid. The DataGrid gives us some powerful pre-built column objects, including command columns which allow the user to press buttons (or links) to select, edit, or delete items in the grid. Imagine you are writing a web form which uses a DataGrid having a "Delete" column, and you want to make the user confirm the deletion before actually deleting the item.

This is accomplished by using some client-side javascript to invoke the confirm function in the onclick handler:

<... onclick="return confirm('Are you sure?');" >
The way that you attach this code to the Delete button is to add to the item's Attributes collection when the item is created:
Control.Attributes.Add("onclick", "return confirm('Are you sure?')");
You will typically find code like this in the Page class which is handling the OnItemCreated event of the grid. It usually goes something like this:
private void InitializeComponent()
  this.grid.ItemCreated += 
    new System.Web.UI.WebControls.DataGridItemEventHandler(
  // ...(other handlers)...

private void OnItemCreated(object sender, 
  System.Web.UI.WebControls.DataGridItemEventArgs e)
  if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == 
    Button btn = e.Item.FindControl("delbutton");
    btn.Attributes.Add("onclick", "return confirm('Are you sure?')");

I find this approach to be flawed for two reasons:

  1. Encapsulation is being violated. Why is it the job for the Page object to fiddle around with the internal attributes of the datagrid? It would be ideal if the page object could simply set a boolean property to enable the confirmation message box.
  2. If you want to have delete confirmations for all 5 grids in all 5 pages of your application, you are going to have to repeat at least some of this code 5 times in your page classes. You can try to work around this by sharing some common code, but you still have to hook up an event handler for each grid in each page's InitializeComponent.

A Better Way

We will derive a new class from DataGrid, called ConfirmDelDataGrid. The derived class will internally handle the code to attach the javascript attributes. In order to take advantage of deletion confirmation, the page class merely has to create an instance of ConfirmDelDataGrid and do nothing else.

Creating a Derived DataGrid

To create the new customized DataGrid, right click on your project in the Class View and select "Add... Class". You must be in the class view! If you try this in the solution explorer, you can only add generic classes to your project. Type a class name and then switch to the Base Class panel. Select the DataGrid as your base class, like this:

Creating a DataGrid subclass

Once you have added your new derived class, we will go about customizing the behavior. First we need a way to determine which column is the Delete column in the grid. One approach is to override the DataGrid's CreateColumnSet method and examine the columns as they are created:
// Class member that stores the index of the "Delete" column of this grid
protected int delcol = -1;

protected override ArrayList CreateColumnSet(PagedDataSource dataSource, 
  bool useDataSource)
  // Let the DataGrid create the columns
  ArrayList list = base.CreateColumnSet (dataSource, useDataSource);

  // Examine the columns
  foreach (DataGridColumn col in list)
    // If this column is the "Delete" button command column...
    if ((col is ButtonColumn) && 
        (((ButtonColumn)col).CommandName == "Delete"))
      // Found it


  // If we did not find a delete column, invalidate the index
  if (delcol == list.Count) delcol = -1;

  // Done
  return list;

By overriding the CreateColumnSet method we get a chance to examine the columns right after they are created by the DataGrid base class. We figure out which column (if any) is the "Delete" column and store that index in a protected member variable.

Next we will override the OnItemDataBound method of the DataGrid base class. First we let the DataGrid bind the item, then we attach the javascript to the delete column (if any):

// Property to enable/disable deletion confirmation
protected bool confirmdel = true;
public bool ConfirmOnDelete 
  get { return confirmdel; } 
  set { confirmdel = value; } 

protected override void OnItemDataBound(DataGridItemEventArgs e)
  // Create it first in the DataGrid
  base.OnItemDataBound (e);

  // Attach javascript confirmation to the delete button
  if ((confirmdel) && (delcol != -1))
          "return confirm('Are you sure?')");

So that is the code internal to the DataGrid. Notice that the new behavior is built-in to the class and a Page object who uses the class does not need to do anything to enable the deletion confirmation message box.

Putting it All Together

Now comes the beautiful part. Once we have created our derived DataGrid class called ConfirmDelDataGrid, using it and leveraging its new built-in functionality is a snap. First, add a @Register tag on the .aspx page to register the datagrid class and use it rather than <asp:DataGrid>:
<%@ Register tagprefix="dg" Namespace="ooaspnet" Assembly="ooaspnet" %>
<!--<span class="code-comment"> (page layout & design here)... --></span>
<dg:ConfirmDelDataGrid id="grid" runat="server" ..... >

You'll also need to set the code-behind in your .cs file to use the new derived class:

protected ConfirmDelDataGrid grid;

private void Page_Load(object sender, System.EventArgs e)
  if (!IsPostBack)
    grid.ConfirmOnDelete = true;
    grid.DataSource = new string[4] { "red", "green", "blue", "purple" };

This is as simple as it gets. We have a new DataGrid subclass with a property that lets us automatically add confirmation message boxes, without knowing (or caring) at the Page level how it works.

Also, if we ever decide to improve the code for attaching the javascript, we can just modify the code inside the ConfirmDelDataGrid class once. Every page that uses this class will automatically benefit from the changes.


Programming ASP.NET allows us to take advantage of the powerful features of the underlying languages that we use. We can use object-oriented design features such as inheritance and encapsulation to develop re-usable classes that work autonomously and do not require glue code on the Page objects.


This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


About the Author

Los Guapos
Web Developer
United States United States
No Biography provided

You may also be interested in...

Comments and Discussions

Generalgetting at the datagrid items Pin
tristian23-Nov-04 6:30
susstristian23-Nov-04 6:30 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170326.1 | Last Updated 11 Aug 2003
Article Copyright 2003 by Los Guapos
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid