By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
448,490 Members | 1,260 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 448,490 IT Pros & Developers. It's quick & easy.

Sorting on GridView

P: 5
Hello All,

I have a grid view that allows sorting, paging, editing, etc.

Under On Load event, if I check: if(!IsPostBack){ DisplayData(); }, the Edit portion works fine. However, the Sorting and paging portions won't. If I just call the DisplayData() method then the Edit portion doesn't work. I found out that when sorting the sorting value doesn't persist and I need to store it elsewhere when doing postbacks, but the code below is already doing it.


Any help is greatly appreciated.

//here is part of the code that I'm having problems with


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)
{
GridView1.DataSource = SortDataTable(GridView1.DataSource as DataTable, true);
GridView1.PageIndex = e.NewPageIndex;
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();
}
}

protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
GridViewSortExpression = e.SortExpression;
int pageIndex = GridView1.PageIndex;
GridView1.DataSource = SortDataTable(GridView1.DataSource as DataTable, false);
GridView1.DataBind();
GridView1.PageIndex = pageIndex;
}
Jun 25 '08 #1
Share this Question
Share on Google+
1 Reply


nateraaaa
Expert 100+
P: 663
Try using Session instead of ViewState to save the SortDirection.

[font=Verdana][size=2]Nathan[/size][/font]
Jun 26 '08 #2

Post your reply

Sign in to post your reply or Sign up for a free account.