Wednesday, August 12, 2009
GridView (non-object/sql DataSource) Paging and Sorting
This is just a quick reminder post about how to do things and in what order to get Paging and Sorting working together on a GridView Control when you’re datasource is NOT a SqlDataSource or ObjectDataSource reference by DataSourceId in the ASPX file but rather a (collection of) POCO objects or other datasource!
.ASPX file
<asp:GridView CssClass="tableStyle1" HeaderStyle-CssClass="bgA" RowStyle-CssClass="bgB"
DataKeyNames="Id" AlternatingRowStyle-CssClass="bgB" AllowPaging="true"
AllowSorting="true" PageSize="50" OnPageIndexChanging="ResultsGrid_PageIndexChanging"
AutoGenerateColumns="false" runat="server" ID="ResultsGrid" OnRowDataBound="ResultsGrid_RowDataBound"
OnSorting="ResultsGrid_Sorting" PagerStyle-ForeColor="White">
<Columns>
<asp:BoundField DataFi
.CS file
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
ViewState["SortExpression"] = "Title";
ViewState["SortDirection"] = "ASC";
}
}
public void ResultsGrid_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
ResultsGrid.PageIndex = e.NewPageIndex;
BindResultGrid();
}
private void BindResultGrid()
{
SqlDataAdapter da = new SqlDataAdapter("ReportingSelect", new SqlConnection(connectionString));
GetSqlParametersForFilter(PrepareFilterTerms(), da.SelectCommand);
DataSet results = new DataSet();
da.Fill(results);
ResultsGrid.DataSource = ApplySorting(results.Tables[0].DefaultView);
ResultsGrid.DataBind();
}
private DataView ApplySorting(DataView dataViewForSorting)
{
dataViewForSorting.Sort = ViewState["SortExpression"].ToString() + " " + ViewState["SortDirection"].ToString();
return dataViewForSorting;
}
public void ResultsGrid_Sorting(object sender, GridViewSortEventArgs e)
{
if (e.SortExpression.ToString() == ViewState["SortExpression"].ToString())
{
if (ViewState["SortDirection"].ToString().StartsWith("ASC"))
{
ViewState["SortDirection"] = "DESC";
}
else
{
ViewState["SortDirection"] = "ASC";
}
}
else
{
ViewState["SortExpression"] = e.SortExpression.ToString();
if (e.SortDirection == SortDirection.Ascending)
{
ViewState["SortDirection"] = "ASC";
}
else
{
ViewState["SortDirection"] = "DESC";
}
}
BindResultGrid();
}
No comments:
Post a Comment