Question about grids and sorting

  • Thread starter Thread starter adriank
  • Start date Start date
A

adriank

I'm trying to make a sortable grid. I get the grid the first time the
page loads, then I click on the column name, and the page reloads with
an empty grid (only headers are shown). Any idea?

This is the code:

private void Page_Load(object sender, System.EventArgs e)
{

if ( !IsPostBack)
{

daEvents.Fill(dsEvents);
dgEvents.DataBind();
}


}

private void dgEvents_SortCommand(object source,
System.Web.UI.WebControls.DataGridSortCommandEventArgs e)
{

daEvents.Fill(dsEvents);
dsEvents.eventsTBL.DefaultView.Sort = e.SortExpression;
dgEvents.DataBind();

}
 
Adriank:

Your dataset is probably being reset at the post back. Just to be safe, try
adding the Dataset to Session state when you first populate it. Then use the
SessionState dataset when you try to sort. Here's a sample routine I used
which uses the session variable "Data_Table" which is stored when I first
load the grid:

First, set the sort command of the grid to this sub:

Private Sub dglogs_SortCommand(ByVal source As Object, ByVal e As
System.Web.UI.WebControls.DataGridSortCommandEventArgs) Handles
dglogs.SortCommand
BindData(e.SortExpression)
End Sub

Then set the allow sort to true.

Now just create a new view based on the DataTable or dataset stored in
session state. I create a new dataview each time in this example, but you
could store the view in state as well and just change the sort criteria.

Protected Sub BindData(ByVal sortField As String)
Try
If cboPages.SelectedItem.Value = "All" Then
dglogs.AllowPaging = False
Else
dglogs.AllowPaging = True
dglogs.PageSize = CType(cboPages.SelectedItem.Value, Int32)
End If
Dim dvw As DataView
dvw = CType(Session("Data_Table"), DataTable).DefaultView
dvw.Sort = sortField
dglogs.DataSource = dvw
dglogs.DataBind()
Catch sq As SqlException
Console.Write(sq.ToString)
Catch exc As System.Exception
Console.WriteLine(exc.ToString)
End Try

End Sub
 
Back
Top