<asp:DataGrid AllowSorting =True OnSortCommand='SortData' id='DataGrid1' runat='server' EnableViewState='false'></asp:DataGrid>
VB.NET
Private Sub Page_Load(sender As Object, e As System.EventArgs)
’ Put user code to initialize the page here
Dim arrlist As New ArrayList()
arrlist.Add('Tips')
arrlist.Add('Tricks')
arrlist.Add('Code')
arrlist.Add('Samples')
DataGrid1.DataSource = arrlist
DataGrid1.DataBind()
ViewState('AList') = arrlist
End Sub ’Page_Load
Protected Sub SortData([source] As [Object], e As System.Web.UI.WebControls.DataGridSortCommandEventArgs)
If ViewState('SortOrder') Is Nothing Then
SortAsc()
Else
If ViewState('SortOrder').ToString() = ' ASC' Then
SortDesc()
Else
SortAsc()
End If
End If
End Sub ’SortData
Sub SortAsc()
ViewState('SortOrder') = ' ASC'
CType(ViewState('AList'), ArrayList).Sort()
DataGrid1.DataSource = ViewState('AList')
DataGrid1.DataBind()
ViewState('Sort') = 'DESC'
End Sub ’SortAsc
Sub SortDesc()
ViewState('SortOrder') = ' DESC'
CType(ViewState('AList'), ArrayList).Sort()
CType(ViewState('AList'), ArrayList).Reverse()
DataGrid1.DataSource = ViewState('AList')
DataGrid1.DataBind()
ViewState('Sort') = 'ASC'
End Sub ’SortDesc
C#
private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
ArrayList arrlist = new ArrayList ();
arrlist.Add ('Tips');
arrlist.Add ('Tricks');
arrlist.Add ('Code');
arrlist.Add ('Samples');
DataGrid1.DataSource = arrlist ;
DataGrid1.DataBind ();
ViewState['AList'] = arrlist ;
}
protected void SortData(Object source, System.Web.UI.WebControls.DataGridSortCommandEventArgs e )
{
if (ViewState['SortOrder'] ==null)
{
SortAsc();
}
else if (ViewState['SortOrder'].ToString () == ' ASC' )
{
SortDesc();
}
else
{
SortAsc();
}
}
void SortAsc()
{
ViewState['SortOrder'] = ' ASC';
((ArrayList)ViewState['AList']).Sort ();
DataGrid1.DataSource = ViewState['AList'];
DataGrid1.DataBind ();
ViewState['Sort']='DESC';
}
void SortDesc()
{
ViewState['SortOrder'] = ' DESC';
((ArrayList)ViewState['AList']).Sort ();
((ArrayList)ViewState['AList']).Reverse ();
DataGrid1.DataSource = ViewState['AList'];
DataGrid1.DataBind ();
ViewState['Sort']='ASC';
}
Permalink