public class MyPage: System.
Web.
UI.
Page
{
protected DataGrid myDataGrid;
private void Page_Load(object sender, System.EventArgs e)
{
if (!Page.IsPostBack)
{
DataBinder();
}
}
// method bind source data to DataGrid control
private void DataBinder()
{
DataView objDataView = new DataView(/* …get DateTable object here … */);
objDataView.Sort = SortExpression;
myDataGrid.DataSource = objDataView;
myDataGrid.DataBind();
}
// property stores latest sort direction of DataGrid between states
public string SortDirection
{
get
{
return Session[“myDataGridSortDirection”] == null
? “ASC”
: Session[“myDataGridSortDirection”].ToString();
}
set
{
Session[“myDataGridSortDirection”] = value;
}
}
// property stores latest sort experession of DateGrid between states
public string SortExpression
{
get
{
return Session[“myDataGridSortExpression”] == null
? “ID”
: Session[“myDataGridSortExpression”].ToString();
}
set
{
Session[“myDataGridSortExpression”] = value;
}
}
// binding event handlers
private void InitializeComponent()
{
this.myDataGrid.ItemCreated
+= new DataGridItemEventHandler(this.myDataGrid_ItemCreated);
this.myDataGrid.SortCommand += new DataGridSortCommandEventHandler(this.myDataGrid_SortCommand);
this.Load += new System.EventHandler(this.Page_Load);
}
// below handler is invoked for render every output item of DataGrid
// this is place and moment when we will add icon image which will show current sort direction
private void myDataGrid_ItemCreated(object sender, DataGridItemEventArgs e)
{
if (e.Item.ItemType != ListItemType.Header) return;
if (!e.Item.HasControls()) return;
foreach (Control control in e.Item.Controls)
{
if (!control.HasControls()) continue;
LinkButton button = (LinkButton)control.Controls[0];
if (button != null && SortExpression.IndexOf(button.CommandArgument) != -1)
{
HtmlImage image = new HtmlImage();
image.Src = “images/sort_”
+ ( SortExpression.IndexOf(“ASC”) != -1
? “asc”
: “desc” )
+ “.gif”;
control.Controls.Add(image);
break;
}
}
}
// sort event handler
private void myDataGrid_SortCommand(object source, DataGridSortCommandEventArgs e)
{
SortExpression = e.SortExpression.ToString() + ” “ + SortDirection;
SortDirection = SortDirection == “ASC” ? “DESC” : “ASC”;
DataBinder();
}
}