Programming Journal C#, Java, SQL and to a lesser extent HTML, CSS, XML, and regex. I made this so other programmers could benefit from my experience.

Wednesday, October 17, 2007

Sorting a GridView that is detached from database and put in a cache

First, the GridView needs to have sorting enabled and a sorting method:


<asp:GridView ID="GridView2" runat="server"
OnSorting="GridView2_Sorting" AllowSorting="True">
</asp:GridView>

Next, the page load and sorting method need to be implemented. I loaded my data from another GridView at the load. There is a Label that is also used. This code is similar to this reference link.


protected void Page_Load(object sender, EventArgs e)
{
DataView myDataView;

// Retrieve the DataView object from Cache. If not exist, then add DataView object to the Cache.

myDataView = (DataView)Cache["MyDataSet"];

if (myDataView == null)
{
myDataView = getTable().DefaultView;
Cache["MyDataSet"] = myDataView;
myDataView.Sort = myDataView.Table.Columns[0].ToString() + " ASC";
lblCacheMsg.Text = "Dataset created explicitly";
}
else
{
lblCacheMsg.Text = "Dataset retrieved from cache";
}
GridView2.DataSource = myDataView;
GridView2.DataBind();
}

// Verbose sort version
protected void GridView2_Sorting(object sender, GridViewSortEventArgs e)
{
DataView Source = (DataView)Cache["MyDataSet"];
string direction = " DESC";
string curDirecton = Source.Sort.ToString().ToUpper();
if (curDirecton.Contains(direction))
{
direction = ASC;
}
else
{
direction = DESC;
}
Source.Sort = e.SortExpression + " " + direction;
Cache["MyDataSet"] = Source;
GridView2.DataSource = Source;
GridView2.DataBind();
lblE.Text = direction;
}
private DataTable getTable()
{
DataTable retVal;
DataTableHelper dth = new DataTableHelper(GridView1);
retVal = dth.getDataTable();
return retVal;
}

3 comments:

Anonymous said...

One of the most powerful grid capabilities is support of both independent and simultaneous processing of data sorting, grouping and filtering. A programmer may use any combination of these operations without any overhead keeping business logic code simple and clear visit for more help dapfor. com

Anonymous said...

Create and add new SortDescriptor to the collection to create sorting for GridView in C#.

Anonymous said...

Sorting in GridView in C#