Ниже приведен пример:
<%@ Page %>
<%@ Import Namespace="System.Data"%>
<html>
<head>
<script runat="server" language="c#">
const string SORT_ASC = "ASC";
const string SORT_DESC = "DESC";
string CurrentDirection {
get {
object direction = ViewState["direction"];
if (direction == null) {
direction = ViewState["direction"] = SORT_ASC;
}
return (string)direction;
}
set {
ViewState["direction"] = value;
}
}
string CurrentField {
get {
object field = ViewState["field"];
if (field == null) {
field = ViewState["field"] = "Name";
}
return (string)field;
}
set {
ViewState["field"] = value;
}
}
DataTable CreateDataSource() {
DataTable dt = new DataTable();
dt.Columns.Add("Name",typeof(string));
dt.Columns.Add("RevName",typeof(string));
const int MAX_ITEMS = 10;
for(int i = 0; i < MAX_ITEMS; i++) {
DataRow dr = dt.NewRow();
dr["Name"] = string.Concat("Item #",i);
dr["RevName"] =
string.Concat("Rev Item #", MAX_ITEMS - i - 1);
dt.Rows.Add(dr);
}
return dt;
}
void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
BindGrid();
}
}
void OnSortGrid(object sender,
DataGridSortCommandEventArgs e) {
string newField = e.SortExpression;
if (newField != CurrentField) {
CurrentField = newField;
CurrentDirection = SORT_ASC;
} else {
if (CurrentDirection == SORT_ASC) {
CurrentDirection = SORT_DESC;
} else {
CurrentDirection = SORT_ASC;
}
}
BindGrid();
}
void BindGrid() {
DataTable dt = CreateDataSource();
dt.DefaultView.Sort = string.Format("{0} {1}",
CurrentField, CurrentDirection);
_grid.DataSource = dt.DefaultView;
_grid.DataBind();
}
</script>
</head>
<body>
<form runat="server">
<asp:DataGrid runat="server" id="_grid"
AllowSorting="true" OnSortCommand="OnSortGrid"/>
</form>
</body>
</html>