Click here to Skip to main content
13,551,021 members
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

GeneralAn easy way to bind 'DELETE confirmation message' to .NET controls Pin
elizas17-Feb-10 1:38
groupelizas17-Feb-10 1:38 
GeneralData Entry Forms Pin
rizee_k15-Aug-05 9:59
memberrizee_k15-Aug-05 9:59 
GeneralCustom Datagrid Pin
Michael Sync7-Dec-04 15:50
memberMichael Sync7-Dec-04 15:50 
Generalgetting at the datagrid items Pin
tristian23-Nov-04 5:30
susstristian23-Nov-04 5:30 
GeneralProblem with multible Submit Buttons in One form Pin
dhanekula24-May-04 2:30
memberdhanekula24-May-04 2:30 
Generalthe active schema doesn not support Pin
ctcraig17-Sep-03 5:36
memberctcraig17-Sep-03 5:36 
GeneralA sound framework lowers business costs - bring on OO Pin
apeterson20-Aug-03 2:57
memberapeterson20-Aug-03 2:57 
GeneralI have a question please... Pin
profoundwhispers19-Aug-03 4:17
memberprofoundwhispers19-Aug-03 4:17 
GeneralRe: I have a question please... Pin
CBoland19-Aug-03 4:56
memberCBoland19-Aug-03 4:56 
The SDK docs are my #1 source for technical information. I think it's the best documentation MS has written for any of their products (that I've read, anyway).

The source code for the Framework is available (at least the reverse-engineered MSIL code is) by using Anakrino. This little gem converts un-obfuscated MSIL code back into C# or C++ code. I've used it many times to find out how a Framework class works. You can get it here:

GeneralRe: I have a question please... Pin
Anonymous19-Aug-03 8:39
sussAnonymous19-Aug-03 8:39 
GeneralRe: I have a question please... Pin
Greg Ennis19-Aug-03 11:26
memberGreg Ennis19-Aug-03 11:26 
GeneralAnother Silly OOP Purist and Fanatic Example Pin
rh200113-Aug-03 1:25
memberrh200113-Aug-03 1:25 
GeneralRe: Another Silly OOP Purist and Fanatic Example Pin
Greg Ennis13-Aug-03 1:34
memberGreg Ennis13-Aug-03 1:34 
GeneralBjarne Stroustrup != GOD Pin
rh200113-Aug-03 10:18
memberrh200113-Aug-03 10:18 
GeneralRe: Bjarne Stroustrup != GOD Pin
Greg Ennis13-Aug-03 11:26
memberGreg Ennis13-Aug-03 11:26 
GeneralRe: Bjarne Stroustrup != GOD Pin
rh200113-Aug-03 11:52
memberrh200113-Aug-03 11:52 
GeneralRe: Bjarne Stroustrup != GOD Pin
MammaMu19-Aug-03 11:11
memberMammaMu19-Aug-03 11:11 
GeneralRe: Another Silly OOP Purist and Fanatic Example Pin
cas413-Aug-03 2:26
membercas413-Aug-03 2:26 
GeneralRe: Another Silly OOP Purist and Fanatic Example Pin
WittnezZ (Claus Witt)13-Aug-03 3:11
memberWittnezZ (Claus Witt)13-Aug-03 3:11 
GeneralDear OOP Fanatics, OOP != Holy Grail ; Comprende? Pin
rh200113-Aug-03 10:04
memberrh200113-Aug-03 10:04 
GeneralRe: Dear OOP Fanatics, OOP != Holy Grail ; Comprende? Pin
Anonymous13-Aug-03 19:31
sussAnonymous13-Aug-03 19:31 
GeneralRe: Dear OOP Fanatics, OOP != Holy Grail ; Comprende? Pin
rh200113-Aug-03 22:02
memberrh200113-Aug-03 22:02 
GeneralOO != Grail? Then what, pray tell... Pin
wik18-Aug-03 16:55
memberwik18-Aug-03 16:55 
GeneralRe: Another Silly OOP Purist and Fanatic Example Pin
Wilco B.16-Aug-03 2:40
memberWilco B.16-Aug-03 2:40 
GeneralRe: Another Silly OOP Purist and Fanatic Example Pin
Oskar Austegard18-Aug-03 13:19
memberOskar Austegard18-Aug-03 13:19 

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
Web03 | 2.8.180515.1 | Last Updated 11 Aug 2003
Article Copyright 2003 by Los Guapos
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid