Monday 23 August 2010

ASP.NET Error: "The DataSource does not support sorting"

In one of our projects we had a GridView which was by default bound to an ObjectDataSource to allow us to Sort/Page and to apply custom filtering. But we also needed to be able to search the data which the GridView is bound to, which we achieved in code and then databound the GridView to the resulting DataTable.

Here's a code snippet:

Before


grdvSummaryGrid.DataSourceID = String.Empty

Dim _clientBLL As New ClientBLL()
grdvSummaryGrid.DataSource = _clientBLL .Search(e.SearchText)
grdvSummaryGrid.DataBind()

Using this code, a problem arose where if you sorted the GridView and then carried out a search, an error resulted when the code attempted to DataBind it to the resulting table:

"System.NotSupportedException: The data source does not support sorting"

I tried a few things and considered creating an ObjectDataSource in code with the search results and then binding the GridView to that, but the answer turned out to be simple.

Before setting the DataSourceID of the GridView to an empty string to allow you to set its DataSource to the resulting DataTable (you can't set both properties), you clear the sort expression.

Like this:

After (Notice the new first line)

grdvSummaryGrid.Sort("", SortDirection.Ascending)
grdvSummaryGrid.DataSourceID = String.Empty

Dim _clientBLL As New ClientBLL()
grdvSummaryGrid.DataSource = _clientBLL .Search(e.SearchText)
grdvSummaryGrid.DataBind()

That did the job. Lots of people seem to have had this problem too, so hopefully this answer will be useful.

3 comments:

Anonymous said...

Thank you very much! This solved my sorting problem hdm

Anonymous said...

Thanks a lot.. It worked for me too...

Anonymous said...

great.. Helped solve my problem.. thank you