DataGrid Sorting

Chapter 5 - Reading Data using the Dataset Object
byJohn Kauffman, Fabio Claudio Ferracchiatiet al.?
Wrox Press ?2002

Among its other abilities, the ASP.NET DataGrid control contains the tools you need to set up data sorting with automatic, in-grid hyperlinks for the user. You just have to understand how to set it up (it works in conjunction with DataView objects), and how to react to the visitors' requests. In outline, the process of sorting within a DataGrid has these steps:

  • Create a DataGrid with specific properties that support sorting

  • Create a single, generic DataView object that can accept a string for its sort order

  • Create a public variable to hold the DataView's sort string

  • Create three procedures for:

    • Dealing with the general data binding

    • Setting the sort string on first load of the page

    • Setting the sort string when a sort has been requested by the visitor

The first of these steps - fixing the DataGrid settings - is simple. As usual, our DataGrid must be within a <form> element that's set to run at the server. In addition, we set the AllowSorting attribute to True, which will automatically change our column headings into clickable text. This is a standard format that the majority of visitors will recognize as indicating that they can sort the records by that column.

click to expand

Also in the DataGrid control, we must set the OnSortCommand attribute to MySortingSub, where the latter is the name of the handler that will implement the sorting functionality.

In step two, you'll recall from our section on DataView objects that we can create a DataView for a particular DataTable, and then set its Sort property in a later command.

For the third step, the variable that holds the sort string must be available to all our handlers, so we'll need to place it within the <script> element, but outside any other code. We will also need to use the Public keyword, rather than Dim.

Last of all, we create three procedures:

  • The first is called SetData(). It creates our connection, data adapter, DataSet, and DataView objects, and queries the database.

  • The second is the Page_Load() event handler, which sets the DataView to use and then executes SetData().

  • The third is an event handler called SortColumn(). It changes the sort order and then executes SetData().

The key to getting this kind of ASP.NET page to function correctly is to understand how the three handlers interact: when they're called, and how information flows between them. We'll examine exactly what goes on in our next example, but first we need to study the two arguments that have been passed to every event handler we've written so far: Source and E. We've been faithfully typing their names, but never actually using them. That's going to change here, and there are three points to be aware of:

  • The Source parameter is the name of (and therefore a reference to) the object that called the procedure.

  • In many cases, we must change the keyword EventArgs to be more specific to the kind of event that invoked the handler. If it were to be invoked by a SortCommand event, for example, then EventArgs should be changed to DataGridSortCommandEventArgs.

  • An event can pass one or more arguments to a handler, as properties of the object E. In our case, the argument is called SortExpression and can be read using E. SortExpression.

Try It Out - DataGrid Sorting

start example

Suppose that we want to display a table of employees that can be sorted by EmployeeID, Name, or Country. To add a little complexity, in the case of the latter we want to sort within a country by the employee's last name.

  1. Create a new file named DataGrid_sorting.aspx in the ch05 folder, and then enter the following code:

     <%@ Import namespace="System.Data" %> <%@ Import namespace="System.Data.SqlClient" %> <html>   <head><title>DataGrid Sorting</title></head>   <body>     <h3>DataGrid Sorting</h3>     <form runat="server">       <asp:DataGrid  runat="server"                     AllowSorting="True"                     OnSortCommand="SortColumn" />     </form>   </body> </html> <script language="VB" runat="server"> Public strViewString As String Sub SetData()   ' Connection setup   Dim strConnection As String = ConfigurationSettings.AppSettings("NWind")   Dim objConnection As New SqlConnection(strConnection)   ' DataAdapter setup   Dim strSQL As string = "SELECT EmployeeID, FirstName, LastName, " & _                          "Country FROM Employees"   Dim objAdapter As New SqlDataAdapter(strSQL, objConnection)   ' DataSet & Adapter & Table   Dim objDataSet As New DataSet()   objAdapter.Fill(objDataSet, "dtEmployees")   Dim dtEmployees As DataTable = objDataSet.Tables("dtEmployees")   ' Create DataView on dtEmployees   Dim dvView As New DataView(dtEmployees)   dvView.Sort = strViewString   ' Bind data   dgEmployees.DataSource = dvView   dgEmployees.DataBind() End Sub Sub Page_Load(Source As Object, E As EventArgs)   If Not Page.IsPostBack Then     strViewString = "LastName"     SetData()   End If End Sub Sub SortColumn(Source As Object, E As DataGridSortCommandEventArgs)   If E.SortExpression = "Country" Then     strViewString = "Country, LastName"   Else     strViewString = E.SortExpression   End If   SetData() End Sub </script> 

  2. The above ASPX page yields a display that looks like the one below:

    click to expand

  3. Clicking the Country column heading will re-sort the rows according to country:

    click to expand

end example

How It Works

We'll analyze this page in the same four parts that we discussed in the theory section above. First, ensuring that the DataGrid control is inside a <form runat="server"> element, we set two properties as follows:

        <form runat="server">          <asp:DataGrid  runat="server"                        AllowSorting="True"                        OnSortCommand="SortColumn" />        </form> 

Next, right inside the <script> element, we have the Public variable that holds our sort string. strViewString can be used from any of the three procedures that follow it - this is a level of flexibility we'll need, since the variable will hold the name of the column on which we want to sort.

    <script language="VB" runat="server"> Public strViewString As String 

Talking of those three procedures, let's take a look at the first. SetData() creates and uses various objects that we're now familiar with (a connection, a data adapter, a DataSet, and a DataTable called dtEmployees), and then goes on to create a DataView object, setting its Sort property to the contents of our public strViewString variable.

 Sub SetData()   ...   ' Create DataView on dtEmployees   Dim dvView As New DataView(dtEmployees)   dvView.Sort = strViewString   ' Bind data   dgEmployees.DataSource = dvView   dgEmployees.DataBind() End Sub 

There are two occasions in the life of the page when SetData() will be called. The first occurs when the page loads for the first time, through a call in the Page_Load() handler. There, we give the sort order string an initial value of "LastName". Notice the use of Page.IsPostBack in a test to ensure that we don't call SetData() from this code every time the page is reloaded.

 Sub Page_Load(Source As Object, E As EventArgs)   If Not Page.IsPostBack Then     strViewString = "LastName"     SetData()   End If End Sub 

The other time we call SetData() is after a visitor has clicked on a re-sort link (that is, an underlined column heading). In this case, the name of the column on which we wish to sort is contained in the E.SortExpression property, which we assign to strViewString. An exception to this occurs if the SortExpression is Country, in which case we set strViewString to "Country, LastName", as defined by the requirement list for this example.

 Sub SortColumn(Source As Object, E As DataGridSortCommandEventArgs)   If E.SortExpression = "Country" Then     strViewString = "Country, LastName"   Else     strViewString = E.SortExpression   End If   SetData() End Sub 

Note 

If, when writing code like this, you get an error message such as 'SortExpression' is not a member of 'System.EventArgs', then you didn't change EventArgs to the proper object name. There are dozens of these objects, but you can always find the name of the right one by searching the documentation.

The code we've looked at so far hasn't been too difficult, so before we leave this section, we can take a look at a couple of variations that you might like to try. First, if we were to use bound columns, it would be possible to give each column an individual value for its SortExpression property, rather than just getting the column header. Setting a string such as "myColumn1 ASC, myColumn2 DESC", would avoid the need for the If structure in the SortColumn() handler - we'd just set strViewString to E.SortExpression in all cases.

Second, we could react to the click not by changing the DataView object's sort property, but by creating a new SQL statement. This is fundamentally different, because changing a DataView works on the data in the DataSet object, while changing the query results in the DataSet containing the information in a different order. Usually, the ADO.NET solution is more efficient, but it never hurts to do a little testing.



Beginning ASP. NET 2.0 and Databases
Beginning ASP.NET 2.0 and Databases (Wrox Beginning Guides)
ISBN: 0471781347
EAN: 2147483647
Year: 2004
Pages: 263

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net