This tutorial will cover how to handle the Command Event property using ASP.NET C#

In this tutorial we will cover how the handle Command Event by implementing two button controls to sort; ascending and descending. In this case, the two button controls will list items displayed by the BulletedList control when clicked.

Here is a snapshot of how the application will look like:

To start, open Visual Studio 2008. File > New > Web site > ASP.NET Web site and name it sort or whatever you want. Make sure that you include using System.Collections.Generic;

From the Design View, drag over two button controls and assign them the values listed below:

Notice how both Button controls include CommandName and CommandArgument properties. Additionally, we have both Button controls wired to the same Sort_Command() event handler.

Next, from the Design View locate the standard tab of the Toolbox, and drag over a bulleted list. Assign it the same value as below:

Switch to your code behind and let’s add some logic for these event handlers.

First, lets populate the page when it loads with these values below. So within the Page_Load event:

This lets our page know that we have a list of data and we need to add things to it.

Next, we need to add an event handler that checks the CommandName and CommandArguement properties when determining how the elements in the BulletedList should be sorted.

Above we created a Command that will determine which function to call during data organization.

The following part of our script is required in order to work correctly. The funciton Page_PreRender() lets the page right before it starts processing that our bltPeople.DataSource = people;. Keep in mind that when we created: private List people = new List(); that we told our page that our list of strings is going to be used in our Bulleted List.

Finally, we have our sort functions. The Sort_Command was designed to handle both button requests for ASC and DESC order. Since we know what we want to do with each function we simply add a basic String.Compare statement that compares two variables and returns them in a given sequence order.

Download Source Files