3.4 Filter and Sort Records Using the DataView Object

After your data is loaded into the data table, you will probably want to be able to view your data using different filters and sort orders. To do this, you can use the DataView object. This How-To goes into detail and shows you how to take advantage of the DataView control to manipulate your data.

Although you can put data into the DataGrid control and let the users sort data using the columns, you want to display a ComboBox control and let users pick a field from the drop-drown list. How can you filter and sort records using the DataView object to present your data in different ways?

Technique

This How-To displays a set of command buttons that display a letter and an extra command button that displays all records. A data adapter, data table, and data view are declared at the form level. The data adapter is created and the DataTable is filled when the form is loaded with all customers. Using a DataColumn object, a combo box is filled by getting the names of each column that is in the data table. You can see this form in action in Figure 3.5.

Figure 3.5. Selecting a letter here limits the data displayed in the DataGrid control.

graphics/03fig05.jpg

Using the command buttons, a routine is called that creates a DataView object, sets the RowFilter property, and then assigns the data view to the DataSource property of a DataGrid control.

Tip

graphics/tip_icon.gif

Although the RowFilter allows you to filter data based on a criteria such as CompanyName Like 'A%', you can set another property to display data based on the state of the row in which data occurs. The property is called RowStateFilter.

You can set the RowStateFilter to one of the following DataViewRowState values in Table 3.5.


Table 3.5. Label, TextBox, and ComboBox Control Property Settings

Setting

Description

Added

New rows

CurrentRows

Current rows including unchanged, new, and modified rows

Deleted

Deleted rows

ModifiedCurrent

A current version, which is a modified version of original data (see ModifiedOriginal)

ModifiedOriginal

The original version (although it has since been modified and is available as ModifiedCurrent)

None

None

OriginalRows

Original rows including unchanged and deleted rows

Unchanged

Unchanged row

The Sort property of the DataView object is used when a column name is chosen from the ComboBox. The current setting of the Sort property is compared to the column name that is chosen. If the Name matches, then the expression DESC is added to the value that is assigned to the Sort property.

Steps

Open and run the VB.NET-Chapter 3 solution. From the main form, click on the command button with the caption How-To 3.4. When the form loads, click on different letters that are displayed. You will see the data grid display different customers based on their first letter.

If you choose a column name from the Column to Sort On ComboBox control, the data grid will then be sorted based on the column chosen.

  1. Create a new Windows Form.

  2. Add a GroupBox control with the text property set to Click on a Letter.

  3. Now you will be creating buttons that you will place within the GroupBox control you just created. The buttons will have their property set as listed in Table 3.6.

    Table 3.6. Buttons Property Settings

    Object

    Property

    Setting

    Button

    Name

    btnA

     

    Caption

    A

    Button

    Name

    btnB

     

    Caption

    B

    Button

    Name

    btnC

     

    Caption

    C

    ...

       

    Button

    Name

    btnZ

     

    Caption

    Z

    Button

    Name

    btnAll

     

    Caption

    All

  4. Add the DataGrid, the Label, and the ComboBox controls shown in Listing 3.6.

    Table 3.7. DataGrid, Label, and ComboBox Controls Property Settings

    Object

    Property

    Setting

    DataGrid

    Name

    dgCustomers

    Label

    Name

    Label1

    Label

    Caption

    Column to Sort On:

    ComboBox

    Name

    cboSortColumns

  5. In the class module for the form, add the following three Private declarations just below the line of code that reads Windows Form Designer generated code. These three objects will be used throughout the form.

    Private modaCust As OleDb.OleDbDataAdapter
    Private mdtCust As DataTable = New DataTable()
    Private mdvCust As DataView = New DataView()
    
  6. Add the following code to the Load event of the form as shown in Listing 3.6. This code starts out by setting up the modaCust data adapter to grab all the customers to fill the data table called mdtCust. Note that at this point, the data grid has not been filled.

    The next task is to load cboSortColumns with the column headings by iterating through each of the data columns in mdtCust and adding them to the Items collection in cboSortColumns. Last, the SetDataViewFilter routine is called. This routine is discussed in step 8.

    Listing 3.6 frmHowTo3_4.vb: Loading the Data Table to Be Used in the Form, and Adding Column Names to a ComboBox Control
    Private Sub frmHowTo3_4_Load(ByVal sender As Object, _
                        ByVal e As System.EventArgs) Handles MyBase.Load
    
            Dim strSQL As String
            Dim dcCurr As DataColumn
    
            '-- Set up the exception catch
            Try
    
                '-- Create the data adapter and fill the data table
                modaCust = New _
                      OleDb.OleDbDataAdapter("Select * From Customers", _
                      (BuildCnnStr("(local)", "Northwind")))
                modaCust.Fill(mdtCust)
    
                '-- Load the column names into the sort ComboBox control
                For Each dcCurr In mdtCust.Columns
                    Me.cboSortColumns.Items.Add(dcCurr.ColumnName)
                Next
    
            SetDataViewFilter("B")
    
            Catch oexpData As OleDb.OleDbException
                MsgBox(oexpData.Message)
            End Try
    
        End Sub
    
  7. For each of the command buttons that has a single letter, add the first subroutine displayed here in Listing 3.7 to each of its Click events. For the btnAll Button control, add the second subroutine to the Click event. Each Button control will pass the letter that it represents to the subroutine called SetDataViewFilter, discussed in the next step. The btnAll code simply passes the empty string.

    Listing 3.7 frmHowTo3_4.vb: Click Events for Each of the Button Controls
    Private Sub btnA_Click(ByVal sender As System.Object, _
                    ByVal e As System.EventArgs) Handles btnA.Click
            SetDataViewFilter("A")
    End Sub
    Private Sub btnAll_Click(ByVal sender As System.Object, _
     ByVal e As System.EventArgs) Handles btnAll.Click
            SetDataViewFilter("")
    End Sub
    
  8. Add the subroutine that is found in Listing 3.8 to the class module of the form. This routine takes the letter value that is passed in strFilterLetter as a parameter. The first task to perform is assigning the DefaultView of the mdtCust DataTable object to the mdvCust data view. Next, the RowFilter property of mdvCust is set to compare the CompanyName column with the Like expression using the strFilterLetter and the % (wildcard). Note that if "" is passed to strFilterLetter, all the records will be listed. Finally, mdvCust is set as the DataSource for dgCustomers, which is the DataGrid control.

    Listing 3.8 frmHowTo3_4.vb: Setting the RowFilter Property for a DataView Object
    Sub SetDataViewFilter(ByVal strFilterLetter As String)
    
            mdvCust = mdtCust.DefaultView
            mdvCust.RowFilter = "CompanyName Like '" & strFilterLetter & "%'"
            dgCustomers.DataSource = mdvCust
    
        End Sub
    
  9. Add the piece of code that is shown in Listing 3.9 to the SelectdIndexChanged event of the cboSortColumns ComboBox control. This routine compares the current setting of mdvCust's Sort property to the current column name chosen in cboSortColumns. If the two are the same, then the column name is assigned to the Sort property with the DESC keyword added on. If not, then the name of the column is assigned to the Sort property.

    Listing 3.9 frmHowTo3_4.vb: Specifying a Column on Which to Sort
    Private Sub cboSortColumns_SelectedIndexChanged(ByVal sender As System.Object,
                    ByVal e As System.EventArgs) _
                      Handles cboSortColumns.SelectedIndexChanged
    
            '-- Check to see if the column is currently the sorted field.
            '   If it is, sort on the column in descending order.
            '   Otherwise, set the sort to the name of column.
    
            If mdvCust.Sort = Me.cboSortColumns.Text Then
                mdvCust.Sort = Me.cboSortColumns.Text & " DESC"
            Else
                mdvCust.Sort = Me.cboSortColumns.Text
            End If
    
        End Sub
    

How It Works

When the user clicks on a letter, the data view is created, and the data grid reflects the new data. When a field is selected from the ComboBox control, the Sort property of the data view is set and the data grid automatically reflects the new sort order, also showing an arrow in the column heading. If the user chooses the field again, the column will sort in descending order.

Comments

Using the DataView object, you can keep track of multiple views of your data and display them for the users' use. You can also access all of the default views of the data tables in your data set using the DefaultViewManager.

Note

graphics/note_icon.gif

Some people might think that the sorting combo box that was added to this example is unnecessary. It was added for two reasons. First, it shows how to use the Sort property of a DataView object. Second, it's convenient for the user. The user might not want to have to scroll over to a column that is not displayed in the data grid. By using the combo box, he can sort on fields that are not currently displayed.