Monday, March 16, 2009

How to Sort or handle Paging in GridView Manually without databinding

The GridView 'GridViewID' fired event PageIndexChanging which wasn't handled.
The GridView 'GridViewID' fired event Sorting which wasn't handled.

private string ConvertSortDirectionToSql(SortDirection sortDirection)
{
string newSortDirection = String.Empty;

switch (sortDirection)
{
case SortDirection.Ascending:
newSortDirection = "ASC";
break;

case SortDirection.Descending:
newSortDirection = "DESC";
break;
}

return newSortDirection;
}

protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
GridViewSortExpression = e.SortExpression;
int pageIndex = this.GridView1.PageIndex;
this.GridView1.DataSource = SortDataTable(GridView1.DataSource as DataTable, false);
this.GridView1.DataBind();
this.GridView1.PageIndex = pageIndex;

}

private string GridViewSortDirection
{
get
{
return ViewState["SortDirection"] as string ?? "ASC";
}

set
{
ViewState["SortDirection"] = value;
}
}



private string GridViewSortExpression
{
get
{
return ViewState["SortExpression"] as string ?? string.Empty;
}
set
{
ViewState["SortExpression"] = value;
}
}



private string GetSortDirection()
{
switch (GridViewSortDirection)
{
case "ASC":
GridViewSortDirection = "DESC";
break;
case "DESC":
GridViewSortDirection = "ASC";
break;
}
return GridViewSortDirection;
}



protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
this.GridView1.DataSource = SortDataTable(this.GridView1.DataSource as DataTable, true);
this.GridView1.PageIndex = e.NewPageIndex;
this.GridView1.DataBind();
}

protected DataView SortDataTable(DataTable dataTable, bool isPageIndexChanging)
{
if (dataTable != null)
{
DataView dataView = new DataView(dataTable);
if (GridViewSortExpression != string.Empty)
{
if (isPageIndexChanging)
{
dataView.Sort = string.Format("{0} {1}", GridViewSortExpression, GridViewSortDirection);
}
else
{
dataView.Sort = string.Format("{0} {1}", GridViewSortExpression, GetSortDirection());
}
}
return dataView;
}

else
{
return new DataView();
}
}

No comments:

Post a Comment