Tuesday, May 8, 2012

Sorting and filtering a DataTable in VB.NET


There's no way to automatically sort a DataTable after it's populated.

A way around this is to sort the DefaultView of the DataTable (or any other DataView associated with the DataTable).

You can achieve this using the Sort property of the DataView. This is a string which specifies the column (or columns) to sort on, and the order (ASC or DESC).

myDataTable.DefaultView.Sort = "myColumnOfChoice DESC";

Works like a charm.

Filtering the contents of the DataTable:


In this function we check if a value is selected in any of the Dropdown lists  and add the value to the condition. In the last an extra condition “1=1” is added so that there will not be any problem is syntax even when no filter condition is selected.


Not the first entry in all DropDown lists is "All". So if that is selected we don't put any condition.

'Result is of type DataTable ans is populated and bound to a grid on Page_load

 Dim strCondition As String = ""

        If (Not ddlSrcState.SelectedIndex = 0) Then
            strCondition += "srcState='" + ddlSrcState.SelectedItem.Text + "' AND "
        End If
        If (Not ddlEquipType.SelectedIndex = 0) Then
            strCondition += " trl_type1='" + ddlEquipType.SelectedItem.Text + "' AND "
        End If
        If (Not ddlSrcCity.SelectedIndex = 0) Then
            strCondition += " srcCity = '" + ddlSrcCity.SelectedItem.Text + "' AND "
        End If
        If (Not ddlDestCity.SelectedIndex = 0) Then
            strCondition += " destCity = '" + ddlDestCity.SelectedItem.Text + "' AND "
        End If


        strCondition += "1=1"

        Result.DefaultView.RowFilter = strCondition
        Result.DefaultView.Sort = "srcState ASC"
        loadsGridView.DataSource = Result
        loadsGridView.DataBind()


No comments:

Post a Comment

Your comments are moderated by your ISP.