Friday, September 11, 2009

Sort Datagridview with multiple columns using BindingSource in VB.NET

Sort Datagridview with multiple columns using BindingSource in VB.NET

 

When you have to sort datagridview with multiple columns then follow the code below. This code is tested with Visual Studio 2005 and VB.net window application.

Here I am making sorting with two columns, first column is dynamic (as user clicked) and second column is fixed (default). You can extend this as per your requirement.

Basically this code will help you to understand how you can do sorting in datagridview with multiple columns.

 

'Declare one shared/Static variable to take care of persisting the state of sort direction

Shared sortDirection As String = " ASC "

 

**dtDataTable is the table which used to bind the DataGridView1

 

Private Sub DataGridView1_ColumnHeaderMouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles DataGridView1.ColumnHeaderMouseClick

 

  Dim dataGridBindingSource As New BindingSource

  dataGridBindingSource.DataSource = dtDataTable

 

  'This is (ID ASC) first column I made it fixed

  Dim defaultColumn As String = "ID ASC"

  Dim sortColumnOrder As New StringBuilder

  Const ASC As String = " ASC "

  Const DESC As String = " DESC "

 

  'This code will sort the grid with secondary column as Option

  If sortDirection = ASC Then

    sortDirection = DESC

  ElseIf sortDirection = DESC Then

    sortDirection = ASC

  End If

 

  'Collect Column name and built Sort string

  sortColumnOrder.Append(DataGridView1.Columns(e.ColumnIndex).Name)

  sortColumnOrder.Append(sortDirection)

  sortColumnOrder.Append(GlobalConstants.COMMA)

  sortColumnOrder.Append(DefaultColumn)

 

  'Sort the Binding Source

  dataGridBindingSource.Sort = sortColumnOrder.ToString()

 

  'Finally Bind the DataGrid with sorted data table source

  Me.DataGridView1.DataSource = dataGridBindingSource

 

 End Sub

 

When user click on the datagridview header, any column to sort then records would be sorted based on the sortColumnOrder string created. For example if user clicks on the second column header to sort then sortColumnOrder string would be

"Second Column ASC/DESC, First Column ASC/DESC"

If user clicks on the fourth column to sort then sortColumnOrder string would be

"Fourth Column ASC/DESC, First Column ASC/DESC" etc

You can make this code to create sort string as per user requirement like

"1st column ASC/DESC, 2nd column ASC/DESC, 3rd column ASC/DESC" etc. 


3 comments:

Irina said...

Works perfect!
Thank you

Anonymous said...

Nice!
only this page does not show properly on firefox...

Anonymous said...

or Chrome.