Click here to Skip to main content
15,881,172 members
Articles / Web Development / ASP.NET
Article

Object-Oriented ASP.NET

Rate me:
Please Sign up or sign in to vote.
4.22/5 (26 votes)
10 Aug 20035 min read 185.3K   1K   58   30
Use the powerful object-oriented features of C# and VB.NET to build re-usable classes in ASP.NET

Introduction

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:

C#
<... 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:
C#
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:
C#
private void InitializeComponent()
{
  this.grid.ItemCreated += 
    new System.Web.UI.WebControls.DataGridItemEventHandler(
    this.OnItemCreated);
  // ...(other handlers)...
}

private void OnItemCreated(object sender, 
  System.Web.UI.WebControls.DataGridItemEventArgs e)
{
  if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == 
       ListItemType.AlternatingItem)
  {
    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:
C#
// 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
  delcol=0;
  foreach (DataGridColumn col in list)
  {
    // If this column is the "Delete" button command column...
    if ((col is ButtonColumn) && 
        (((ButtonColumn)col).CommandName == "Delete"))
    {
      // Found it
      break;
    }

    delcol++;
  }

  // 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):

C#
// 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))
  {
    e.Item.Cells[delcol].Attributes.Add("onclick", 
          "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>:
HTML
<%@ Register tagprefix="dg" Namespace="ooaspnet" Assembly="ooaspnet" %>
<!-- (page layout & design here)... -->
<dg:ConfirmDelDataGrid id="grid" runat="server" ..... >
<dg:ConfirmDelDataGrid>

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

C#
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" };
    grid.DataBind();
  }
}

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.

Conclusion

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.

License

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


Written By
Web Developer
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralAn easy way to bind 'DELETE confirmation message' to .NET controls Pin
elizas17-Feb-10 1:38
elizas17-Feb-10 1:38 
GeneralData Entry Forms Pin
Member 219117815-Aug-05 9:59
Member 219117815-Aug-05 9:59 
GeneralCustom Datagrid Pin
Michael Sync7-Dec-04 15:50
Michael Sync7-Dec-04 15:50 
Generalgetting at the datagrid items Pin
tristian o'brien23-Nov-04 5:30
tristian o'brien23-Nov-04 5:30 
GeneralProblem with multible Submit Buttons in One form Pin
dhanekula24-May-04 2:30
dhanekula24-May-04 2:30 
Generalthe active schema doesn not support Pin
ctcraig17-Sep-03 5:36
ctcraig17-Sep-03 5:36 
GeneralA sound framework lowers business costs - bring on OO Pin
apeterson20-Aug-03 2:57
apeterson20-Aug-03 2:57 
GeneralI have a question please... Pin
profoundwhispers19-Aug-03 4:17
profoundwhispers19-Aug-03 4:17 
GeneralRe: I have a question please... Pin
CBoland19-Aug-03 4:56
CBoland19-Aug-03 4:56 
GeneralRe: I have a question please... Pin
Anonymous19-Aug-03 8:39
Anonymous19-Aug-03 8:39 
GeneralRe: I have a question please... Pin
Los Guapos19-Aug-03 11:26
Los Guapos19-Aug-03 11:26 
GeneralAnother Silly OOP Purist and Fanatic Example Pin
rh200113-Aug-03 1:25
rh200113-Aug-03 1:25 
GeneralRe: Another Silly OOP Purist and Fanatic Example Pin
Los Guapos13-Aug-03 1:34
Los Guapos13-Aug-03 1:34 
GeneralBjarne Stroustrup != GOD Pin
rh200113-Aug-03 10:18
rh200113-Aug-03 10:18 
GeneralRe: Bjarne Stroustrup != GOD Pin
Los Guapos13-Aug-03 11:26
Los Guapos13-Aug-03 11:26 
GeneralRe: Bjarne Stroustrup != GOD Pin
rh200113-Aug-03 11:52
rh200113-Aug-03 11:52 
GeneralRe: Bjarne Stroustrup != GOD Pin
MammaMu19-Aug-03 11:11
MammaMu19-Aug-03 11:11 
GeneralRe: Another Silly OOP Purist and Fanatic Example Pin
cas413-Aug-03 2:26
cas413-Aug-03 2:26 
GeneralRe: Another Silly OOP Purist and Fanatic Example Pin
WittnezZ (Claus Witt)13-Aug-03 3:11
WittnezZ (Claus Witt)13-Aug-03 3:11 
GeneralDear OOP Fanatics, OOP != Holy Grail ; Comprende? Pin
rh200113-Aug-03 10:04
rh200113-Aug-03 10:04 
Hey OOP mind numb robots who are drunk on their own OOP arrogance!

IF you are so smart why don't you have the GUTS to point out "EXACTLY" what wrong with my arguments?

All you can say, Troll, troll, troll...name calling, name calling, name calling, etc.

You just got your A** kicked, plain and simple.

You know nothing about *TRUE and PRACTICAL* encapsulation. And you haven't the guts to admit that OOP has serious limitations and OOP track record in the real world is like or worse than C++

If you need 24/7 OOP expert to program and maintain your code 365 days of the year, then that shows your something is wrong with the code, not the programmer or even the newbie....

Had the thought ever occurred to you that OOP could NOT be the HOLY GRAIL?
GeneralRe: Dear OOP Fanatics, OOP != Holy Grail ; Comprende? Pin
Anonymous13-Aug-03 19:31
Anonymous13-Aug-03 19:31 
GeneralRe: Dear OOP Fanatics, OOP != Holy Grail ; Comprende? Pin
rh200113-Aug-03 22:02
rh200113-Aug-03 22:02 
GeneralOO != Grail? Then what, pray tell... Pin
wik18-Aug-03 16:55
wik18-Aug-03 16:55 
GeneralRe: Another Silly OOP Purist and Fanatic Example Pin
Wilco B.16-Aug-03 2:40
Wilco B.16-Aug-03 2:40 
GeneralRe: Another Silly OOP Purist and Fanatic Example Pin
Oskar Austegard18-Aug-03 13:19
Oskar 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.