Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Sort DataGridView on Multiple columns

Status
Not open for further replies.

Kliot

Programmer
Jan 10, 2003
622
US
I'm trying to find a simple way to allow users to sort a DataGridView on multiple columns by selecting multiple column headers.

For example I want the user to be able to click on the column header for the state column then click on the header for the city column to get the view sorted by state and city.

Any Suggestions, I know I can easily add a button that will sort the binding source on "State, City" but there are a lot of sorting combinations that my users may want to use.

Thanks
Perrin
 
I think what you want would be extremely difficult to code so that it works correctly. Also, this is not "standard" behavior for grid controls, and as a general rule one should try to stick to "standard and expected" behaviors in programs to avoid confusion/frustration in the users.

As an alternative, you could give the users 2 listboxes. The one on the left contains the fields displayed in the datagrid, and the oneon the right will hold any the user selects for sorting. You can make the datagridview's datasource a DataView, and use the DataView's Sort method with the selections in the second listbox to sort the grid.



I used to rock and roll every night and party every day. Then it was every other day. Now I'm lucky if I can find 30 minutes a week in which to get funky. - Homer Simpson

Arrrr, mateys! Ye needs ta be preparin' yerselves fer Talk Like a Pirate Day! Ye has a choice: talk like a pira
 
I finally had a chance to play and found that it was actually very easy to code. I set the columns sort property to "Programmatic" and added the following code.

Code:
    Private Sub MasterDataGridView_ColumnHeaderMouseClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles MasterDataGridView.ColumnHeaderMouseClick
        If Control.ModifierKeys = Keys.Control Then
            MasterBindingSource.Sort += ", " & MasterDataGridView.Columns(e.ColumnIndex).Name
        Else
            MasterBindingSource.Sort = MasterDataGridView.Columns(e.ColumnIndex).Name
        End If
    End Sub

The "Standard" behavior of sorting by clicking on a column header still exists so I'm not concerned about my users getting frustrated or confused. Now they have the added ability to multi column sorts by Control Clicking additional columns. The only thing that is lost is the ability to sort Asc and Des but that would be easy to add back in.


Perrin
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top