Tuesday, May 20, 2008

Implementing Manual Sorting on GridView

Problem:

  • I have GridViews, powered by ObjectDataSources.
  • I wanted to implement sorting
  • Error: DataSource doesn't implement IEnumerable.
  • Went looking it up: too hard
Solution:
  • GetData() method accepts two input parameters: SortName and SortOrder
  • Page.Load method (snippet 1)
  • GridView.Sorting method (snippet 2)
  • ObjectDataSource.Selecting method (snippet 3)
Snippet 1:

  If IsPostBack Then
    Exit Sub
  End If

  ViewState("SortName") = "ColumnName"
  ViewState("SortOrder") = WebControls.SortDirection.Ascending

Snippet 2:
  e.Cancel = True 'Cancel the automatic sort, do it manually

  If ViewState("SortName") = e.SortExpression Then
     ViewState("SortOrder") = Not ViewState("SortOrder")
  Else
     ViewState("SortName") = e.SortExpression     
     ViewState("SortOrder") = e.SortDirection 
  End If

  GridView1.DataBind()
Snippet 3:

Dim iod As IOrderedDictionary = e.InputParameters 
iod("SortName") = ViewState("SortName")
iod("SortOrder") = ViewState("SortOrder")

No comments:

Post a Comment