Wednesday, December 31, 2008

Paging,Sorting in datagrid

Paging and sorting is the most common feature of datagrid. As i am very much used to with ObjectDataSource, i don't have to do anything for implementing Paging and sorting.
Just set the datasource of the gridview to the ObjectDataSource and
set the AllowPaging and AllowSorting property of the grid view to true and
for each column put some SortExpression and
some pagesize for the gridview.
And thats all for implementing the paging and sorting. ObjectDataSource will take care of the remainings for you.
But some situalition arises where i must not use ObjectDataSource, actuaaly not using ObjectDataSource is easier from coding perspective though we have to implement the paging and sorting explicitly. So i used this code, a overloaded version of bindGrid() function to handle the situaltion

protected override void OnInit(EventArgs e)
{
base.OnInit(e);
gvStockCode.Sorting += new GridViewSortEventHandler(gvStockCode_Sorting);
gvStockCode.PageIndexChanging += new GridViewPageEventHandler(gvStockCode_PageIndexChanging);
}

void gvStockCode_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvStockCode.PageIndex = e.NewPageIndex;
bindGrid(); //Call bindgrid without any parameter so that previous sorting is maintained
}

void gvStockCode_Sorting(object sender, GridViewSortEventArgs e)
{
gvStockCode.PageIndex = 0; //Don't change page index if you want to show the old page the user was
if (ViewState["SortDirection"] != null && ViewState["SortExpression"] != null)
{

SortDirection direction = (SortDirection)ViewState["SortDirection"];
string sortExpr = ViewState["SortExpression"].ToString();
if (sortExpr.ToLower() == e.SortExpression.ToLower())
{
direction = direction == SortDirection.Ascending ? SortDirection.Descending : SortDirection.Ascending;
}
bindGrid(e.SortExpression, direction);
}
else
{
bindGrid(e.SortExpression, e.SortDirection);
}
}
protected void Page_Load(object sender, EventArgs e)
{
If(!IsPostBack)
bindGrid();
}
void bindGrid()
{
SortDirection direction = SortDirection.Ascending; //Default Sort Direction
string sortExpr = ""; //Default sort expression, you can put any expression if wanted to be default for grid
if (ViewState["SortDirection"] != null && ViewState["SortExpression"] != null)
{
direction = (SortDirection)ViewState["SortDirection"];
sortExpr = ViewState["SortExpression"].ToString();
}
bindGrid(sortExpr, direction);
}
void bindGrid(string sortExpression, SortDirection sortDirection)
{
DataTable dt = BusinessLogic.FillTable();//Some function declared in BL

DataView dv = new DataView(dt);
if (sortExpression != string.Empty)
{
if (sortDirection == SortDirection.Ascending)
dv.Sort = sortExpression + " ASC";
else
dv.Sort = sortExpression + " DESC";
}
gvStockCode.DataSource = dv;
gvStockCode.DataBind();
ViewState["SortExpression"] = sortExpression;
ViewState["SortDirection"] = sortDirection;
}