I came across this trying to do an admin panel for membership and profiles. I had users first and last name stored in the profiles. Since the default sql profile provider doesn't have a method that I'm aware of to retrive those values and bind to a gridview, I load the username, and "lastname, firstname" field into a datatable and bind that to a gridview. This gridview control needs to act like all the other gridviews with sorting and paging, which is where Ryan's code has been helpful. But the sorting doesn't hold when pages are changed. I made some mods and think I added that functionality it.
Source: http://www.learnasp.com/freebook/learn/cs_GridViewSortingNoDataSourceControl.aspx
1) I put the PopulatePublishersGridView(); in the Page_Init event method. I believe this calls the method once instead of everytime the page loads. The gridview control stores the information on subsequent page loads in the viewstate.
2)I would think that after the GridView control's DataSource is set to a DataTable it would be saved in the ViewState. So if you changed the DataTable in the GridView's DataSource, those changes would be reflected in the GridView and saved in the ViewState.
Continuing with my thought...that means if you sort the table, thus changing the table, then rebind it, thus saving it to the GridView, then those changes would also be reflected in the ViewState so when you change pages of the GridView control, the info would still be sorted.
It doesn't seem to work that way. Maybe I'm missing something more fundamental in how these things work. But I worked around this by saving the sort field in the ViewState after a sort is done and then again sorting in the PageIndexChanged event method. This means when you change page, it retrieves the saved sort field and direction and sorts and then changes page.
3) Just like the GridViewSortDirection, I saved a GridViewSortExpression.
private String GridViewSortExpression
{
get { return ViewState["SortExp"] as String ?? ""; }
set { ViewState["SortExp"] = value; }
}
4)In the "gridViewPublishers_Sorting" event method, I added:
GridViewSortExpression = e.SortExpression;
5)To keep from having redundant code in the Sorting and PageIndexChanging event methods, I created a function for the sorting:
protected DataView SortTable (DataTable dt)
{
DataView dv=new DataView();
if (dt != null)
{
dv = new DataView(dt);
if(GridViewSortExpression != "")
{
dv.Sort = GridViewSortExpression + " " +
GridViewSortDirection;
}
}
return dv;
}
6) I then added:
gridView.DataSource = SortTable(gridView.DataSource as DataTable);
to the PageIndexChanging before the page is changed and replaced code in the Sorting event methods.
7) I haven't fully tested, but it seems to work.