Question How to sort a DataGridView using a collection as a datasource?

lbrunner

New member
Joined
Jul 7, 2010
Messages
2
Programming Experience
3-5
Hello-

Could someone be so kind as to help me understand how to sort a vb.net Datagridview that uses a collection as a datasource?
I can sort the datagridview by clicking on the column header when the datagridview datasource is a datatable, BUT not when the datasource is a collection.

Below is the code i use:
'//grab the list of entries from the db
mcolClassDetails = mclscommon.pfGetClassesCollection(courseCode)
'//make sure it doesn't try to autogenerate new columns grdClasses.AutoGenerateColumns = False
'//bind our datagrid to our arraylist
grdClasses.DataSource = mcolClassDetails
'//default to most recent entry
UIBuilder.ScrollToRow(grdClasses, "Classes", grdClasses.RowCount() - 1)
'//grab the list of entries from the db for this payroll period
mcolClassDetails = mclscommon.pfGetClassesCollection(courseCode)

'//make sure it doesn't try to autogenerate new columns
grdClasses.AutoGenerateColumns = False
'//bind our datagrid to our arraylist
grdClasses.DataSource = mcolClassDetails

'//default to most recent entry
UIBuilder.ScrollToRow(grdClasses, "Classes", grdClasses.RowCount() - 1)



Any help would be greatly appreciated!
 
I order for the grid to sort automatically, the data source must implement the IBindingList interface, which the generic List class doesn't. You need to use a data source that implements that interface AND provides a useful implementation of ApplySort. The DataView class does, which is why it works for a DataTable. Otherwise you would have to define your own class that does provide such an implementation, probably derived from the BindingList class.

In this case, the easier option is probably to simply configure the grid for programmatic sorting, handle the appropriate events of the grid and then call Sort on the List based on which column header was clicked. Go to the documentation for the SortMode property of the DataGridView class and you should be able to find enough information from that page and the links it provides.
 
Thank you

Thank you for your help!
To make matters worse for me, the collection i am using as the datasource of the grid is a collection of custom classes; therefore, the sort doesnt seemt ot be working on them. I am going to change to a datatable for my datasource instead of the collection. this is quite frustrating for me because i thought it was better to use classes and collections.
Thanks again for your help.
 
the collection i am using as the datasource of the grid is a collection of custom classes; therefore, the sort doesnt seemt ot be working on them.
The Sort method will work if you use it properly. Follow the Blog link in my signature and check out my three-part submission on sorting arrays and collections for more information.
 

Latest posts

Back
Top