ASP.NET DataView Paging and Sorting.
Posted: 27/02/2012 Filed under: ASP.NET, Programming | Tags: ASP.NET, DataView, GridView 1 Comment »This post demonstrates the use of the DataView class for simplifying Paging and Sorting operations on a GridView control.
Prior to getting into the workings of it, do note, that I’m using data from Northwind Customers table. Essentially, all I am doing is retrieving the ContactName, CompanyName and Country from all Customers records and returning them as an IEnumerable<T> object in my Data Access Layer.
To begin, I have a GridView control defined with 3 literal controls. Do note, the SortExpression defined on each TemplateField. Also note the OnSorting and OnPageIndexChanging events.
1: <asp:GridView runat="server"
2: ID="customersGrid"
3: CellPadding="5"
4: CellSpacing="3" AutoGenerateColumns="False"
5: AllowSorting="True"
6: OnSorting="CustomersSorting"
7: AllowPaging="True"
8: PageSize="15"
9: OnPageIndexChanging="CustomersPageChaging"
10: CssClass="gridStyle">
11:
12: <Columns>
13: <asp:TemplateField HeaderText="Name" SortExpression="Name">
14: <ItemTemplate>
15: <asp:Literal runat="server" ID="customerName"
16: Text='<%# DataBinder.Eval(Container.DataItem, "Name") %>'>
17: </asp:Literal>
18: </ItemTemplate>
19: </asp:TemplateField>
20:
21: <asp:TemplateField HeaderText="Company" SortExpression="Company">
22: <ItemTemplate>
23: <asp:Literal runat="server" ID="customerCompany"
24: Text='<%# DataBinder.Eval(Container.DataItem, "Company") %>'>
25: </asp:Literal>
26: </ItemTemplate>
27: </asp:TemplateField>
28:
29: <asp:TemplateField HeaderText="Country" SortExpression="Country">
30: <ItemTemplate>
31: <asp:Literal runat="server" ID="customerCountry"
32: Text='<%# DataBinder.Eval(Container.DataItem, "Country") %>'>
33: </asp:Literal>
34: </ItemTemplate>
35: </asp:TemplateField>
36: </Columns>
37: </asp:GridView>
Then on the code-behind, I’ve set up a property called SortOrder. This property keeps track of the ViewState[“SortOrder”] value that is saved on page postbacks.
1: public string SortOrder
2: {
3: get
4: {
5: if (ViewState["SortOrder"].ToString() == "DESC")
6: {
7: ViewState["SortOrder"] = "ASC";
8: }
9: else
10: {
11: ViewState["SortOrder"] = "DESC";
12: }
13:
14: return ViewState["SortOrder"].ToString();
15: }
16: set
17: {
18: ViewState["SortOrder"] = value;
19: }
20: }
The Page_Load method, sets the SortOrder property to an empty string, then calls a custom method to bind the data to the GridView control.
1: protected void Page_Load(object sender, EventArgs e)
2: {
3: if(Page.IsPostBack) return;
4:
5: ViewState["SortOrder"] = "";
6: BindCustomersGrid("","");
7: }
The custom bind method that is called from the Page_Load method takes in 2 string parameters. The parameters define the sort expression and the sort direction.
The method first checks if the sort expression is not an empty string. If it isn’t empty it then proceeds to use the DataView Sort property, prior to binding the data to the GridView control.
1: private void BindCustomersGrid(string sortExp, string sortDir)
2: {
3: // Custom method is called and DataView object is returned.
4: var view = GetCustomerData();
5:
6: // Check if Sort Expression is available.
7: if (sortExp != string.Empty)
8: {
9: view.Sort = string.Format("{0} {1}", sortExp, sortDir);
10: }
11:
12: // Bind data to GridView control.
13: customersGrid.DataSource = view;
14: customersGrid.DataBind();
15: }
The custom method that returns the DataView object as shown in snippet above, is define in snippet below.
1: private static DataView GetCustomerData()
2: {
3: // Initialise and construct new DataTable
4: using (var table = new DataTable())
5: {
6: table.Columns.Add("Name", typeof(string));
7: table.Columns.Add("Company", typeof (string));
8: table.Columns.Add("Country", typeof (string));
9:
10: // Retrieve customer records from database layer
11: // and populate DateTable rows.
12: foreach (var customer in CustomerData.GetAllCustomers())
13: {
14: table.Rows.Add(customer.Name, customer.Company, customer.Country);
15: }
16:
17: return table.DefaultView;
18: }
19: }
Now we come to the core part of this post. How do we perform sorting? Well, if you have followed the snippets along you would have noticed the custom bind method takes in 2 parameters. It then checks the sort expression parameter for a value, then uses the DataView Sort property to apply the sorting. Not too complex, but the easier bit is on the GridView OnSorting event as show below. Basically, calling the custom bind method by passing in both, the sort expression and the sort order.
1: protected void CustomersSorting(object sender, GridViewSortEventArgs e)
2: {
3: // Sorting is performed by calling custom bind method and specifying
4: // sort expression as defined in GridView control and the SortOrder
5: // property value.
6: BindCustomersGrid(e.SortExpression, SortOrder);
7: }
Now to the next part of the post which is, How do we perform paging?. Well, on the GridView OnPageIndexChanging event, a new page index is set based on the GridViewPageEventArgs passed in, then the custom bind method is called again.
1: protected void CustomersPageChaging(object sender, GridViewPageEventArgs e)
2: {
3: customersGrid.PageIndex = e.NewPageIndex;
4: BindCustomersGrid("", "");
5: }
Hope the post helps show how easy it is to get Paging and Sorting operations working, through the use of a DataView object.
GridView Paging
Posted: 13/09/2011 Filed under: Programming | Tags: ASP.NET, GridView Leave a comment »One of the simplest examples around and I keep forgetting it. It’s as below:
protected void gvControl_PageIndexChaging(object sender, GridViewPageEventArgs e)
{
this.gvControl.PageIndex = e.NewPageIndex;
this.BindData(); // private method that binds the data source
}
A big thank you to the author of this post.
Data Binding Error Object reference not set to an instance of an object.
Posted: 21/07/2011 Filed under: Uncategorized | Tags: DataBinding, Error, GridView Leave a comment »I got the error (as below) attempting to bind list items (SPListItemCollection) into a GridView control.
Obviously this meant that there were null objects coming through. One way to avoid this is error, is to check if the fields within the list are not null and then also handle the above mention error.
// get item object from item collection SPListItem oItem = oItemGroup[i]; // get fields from item object colSampleName = oItem["Sample Name"]; object colSampleDate = oItem["Sample Date"]; if((colSampleName != null) && (colSampleDate != null)) { // databinding operations } // handle exception
Hope this helps.