Logo

Navigation
  • Home
  • Services
    • ERP Solutions
    • Implementation Solutions
    • Support and Maintenance Solutions
    • Custom Solutions
    • Upgrade Solutions
    • Training and Mentoring
    • Web Solutions
    • Production Support
    • Architecture Designing
    • Independent Validation and Testing Services
    • Infrastructure Management
  • Expertise
    • Microsoft Development Expertise
    • Mobile Development
    • SQL Server Database and BI
    • SAP BI, SAP Hana, SAP BO
    • Oracle and BI
    • Oracle RAC
  • Technical Training
    • Learn Data Management
      • Business Intelligence
      • Data Mining
      • Data Modeling
      • Data Warehousing
      • Disaster Recovery
    • Learn Concepts
      • Application Development
      • Client Server
      • Cloud Computing Tutorials
      • Cluster Computing
      • CRM Tutorial
      • EDI Tutorials
      • ERP Tutorials
      • NLP
      • OOPS
      • Concepts
      • SOA Tutorial
      • Supply Chain
      • Technology Trends
      • UML
      • Virtualization
      • Web 2.0
    • Learn Java
      • JavaScript Tutorial
      • JSP Tutorials
      • J2EE
    • Learn Microsoft
      • MSAS
      • ASP.NET
      • ASP.NET 2.0
      • C Sharp
      • MS Project Training
      • Silverlight
      • SQL Server 2005
      • VB.NET 2005
    • Learn Networking
      • Networking
      • Wireless
    • Learn Oracle
      • Oracle 10g
      • PL/SQL
      • Oracle 11g Tutorials
      • Oracle 9i
      • Oracle Apps
    • Learn Programming
      • Ajax Tutorial
      • C Language
      • C++ Tutorials
      • CSS Tutorial
      • CSS3 Tutorial
      • JavaScript Tutorial
      • jQuery Tutorial
      • MainFrame
      • PHP Tutorial
      • VBScript Tutorial
      • XML Tutorial
    • Learn Software Testing
      • Software Testing Types
      • SQA
      • Testing
  • Career Training
    • Career Improvement
      • Career Articles
      • Certification Articles
      • Conflict Management
      • Core Skills
      • Decision Making
      • Entrepreneurship
      • Goal Setting
      • Life Skills
      • Performance Development
      • Personal Excellence
      • Personality Development
      • Problem Solving
      • Relationship Management
      • Self Confidence
      • Self Supervision
      • Social Networking
      • Strategic Planning
      • Time Management
    • Education Help
      • Career Tracks
      • Essay Writing
      • Internship Tips
      • Online Education
      • Scholarships
      • Student Loans
    • Managerial Skills
      • Business Communication
      • Business Networking
      • Facilitator Skills
      • Managing Change
      • Marketing Management
      • Meeting Management
      • Process Management
      • Project Management
      • Project Management Life Cycle
      • Project Management Process
      • Project Risk Management
      • Relationship Management
      • Task Management
      • Team Building
      • Virtual Team Management
    • Essential Life Skills
      • Anger Management
      • Anxiety Management
      • Attitude Development
      • Coaching and Mentoring
      • Emotional Intelligence
      • Stress Management
      • Positive Thinking
    • Communication Skills
      • Conversation Skills
      • Cross Culture Competence
      • English Vocabulary
      • Listening Skills
      • Public Speaking Skills
      • Questioning Skills
    • Soft Skills
      • Assertive Skills
      • Influence Skills
      • Leadership Skills
      • Memory Skills
      • People Skills
      • Presentation Skills
    • Finding a Job
      • Etiquette Tips
      • Group Discussions
      • HR Interviews
      • Interview Notes
      • Job Search Tips
      • Resume Tips
      • Sample Resumes
 

ASP.NET Adding Sorting and Paging in GridView

By Exforsys | on September 10, 2005 |
ASP.NET 2.0

Adding Sorting and Paging in GridView

In this tutorial you will learn adding sorting and paging in a GridView Control, Implement Two Column Sorting, Create Code for Custom Sorting, Editing the GridView control data, Deleting Displayed Records, Inserting Records and Using Templates.

Adding Sorting and Paging

Sorting and paging can be added to the GridView control without writing any code.

1. In Design view, right-click the GridView control, and then click Show Smart Tag.

2. On the GridView Tasks menu, select the Enable Sorting box.

3. The column headings in the GridView control change to links.

4. On the GridView Tasks menu, select the Enable Paging box.

5. A footer is added to the GridView control with page number links.

6. Optionally, use the Properties window to change the value of the PageSize property from 10 to a smaller page size.

7. Press CTRL+F5 to run the page.

8. The GridView control is displayed with StudentID, StudentName, StudentAge and CourseId columns. The column headings can be clicked to sort by the contents of that column.

9. Close the browser.

Implementing Two Column Sorting

At this point, the contents of the table can be sorted on the basis of a single column. However, there may be situations where the developer needs to provide an interface to sort data on the basis of two or more columns. To implement two-column sorting, custom sorting features may be added. In this section, let us add a DropDownList control to specify a second column to sort the grid. The DropDownList control will display the names of columns from the StudentMaster table that users can sort by.

1. In the Default.aspx page, switch to Design view.

2. In the Toolbox, from the Standard group, drag a DropDownList control onto the page.

3. Right-click the DropDownList control, click Show Smart Tag, and then on the Common DropDownList Tasks menu, click Edit Items.

4. In the ListItem Collection Editor dialog box, click Add, and set Text and Value to StudentName.

5. Click Add to add another list item, and then set Text and Value to CourseId.

6. Click Add, and then set Text and Value to StudentAge.

7. Click Add, and then set Text and Value to StudentId.

8. Set Selected to True.

9. Click OK.

10. On the Common DropDownList Tasks menu, select the Enable AutoPostBack box.

11. In the Toolbox, from the Standard group, drag a Label control onto the page.

12. Right-click the Label control, click Properties, and then set ID to LabelSortDisplay.
Creating Code for Custom Sorting

For custom sorting, we now write an event handler for the GridView control’s Sorting event. The Sorting event is raised when the user clicks a column heading in the GridView control.

To add an event handler for the Sorting event 1. If you are working with a single-file page, switch to Source view and then add the following directives to the top of the code page:

< % @ Import Namespace="System.Data" % >
< % @ Import Namespace="System.Data.SqlClient" % >

2. Importing the namespaces will make it easier to write the code needed.

3. If the application is using a code-behind page, switch to the code-behind page Default.aspx.cs and add the following lines to the top of the code file, outside the class declaration:

using System.Data;
using System.Data.SqlClient;

4. In the Default.aspx page, switch to Design view, right-click the DropDownList control, and then click Properties.

5. In the Properties window toolbar, click the Events icon, and then double-click SelectedIndexChanged to create a skeleton event handler.

6. Insert the following highlighted code into the event handler.

Click here to view sample code

This code intercepts the SelectedIndexChanged event for DropDownList1 to specify the second sort parameter based on the value selected. Then, it retrieves the sortorder from the Session state and adds the " ASC" or " DESC" to the Sort property for the DataView. Finally, it rebinds the GridView control to the data.

7. Switch to the Default.aspx page and select the DropDownList control.

8. In the Properties window toolbar, click the Events icon, and then double-click Load to create a skeleton event handler.

9. Insert the following highlighted code into the Page_ Load event handler.

Click here to view sample code

10. This code handles the Page Load event and retrieves the ConnectionString connection string from the Web.config file to execute a SELECT statement using a sqlDataAdapter control. Then, it fills a dataset with the data returned, selects the first table of the dataset as a DataView object, for sort operations, and then saves the DataView object in the Session state such that subsequent sorts do not require a round trip to the database. Finally, it sets the default sort order to Ascending in Session state.

11. Switch to Design view.

12. Right-click the GridView1 control, click Properties, and then set DataSourceID to (None) to remove it.

13. Because you are setting the data source in code, the GridView control cannot also have a DataSourceID property setting.

14. When prompted to refresh the fields and keys for the GridView control, click No.

15. Although you are changing the data source for the GridView control (by removing it), you want to retain the existing field bindings.

16. Right-click the GridView1 control, and then click Properties.

17. In Properties, click Events, and then double-click Sorting to create a skeleton event handler.

18. Add the following highlighted code to the Sorting event handler:

Click here to view sample code

This code handles the sorting event of the GridView control to customize the sort functionality of the GridView control. It uses the sorting functionality of the underlying DataView control. It retrieves the DataView control saved in the Session state. Then, it retrieves the sort order value from Session state and adds " ASC" or " DESC" to theSortExpression property passed to the event handler. It saves the new sort order and the SortExpression value in the Session state. Finally, it displays the SortExpression value in a Label control and rebinds the GridView control to the data. The page can now be tested.

 

2. The GridView control is displayed with StudentId, StudentName, StudentAge, and CourseId columns. Click a column heading to sort by the contents of that column.

 

 

Editing the GridView Control Data

The GridView control already contains all the functions necessary for editing data, since the control is abstract and generic. In fact this is the greatest strength of the GridView control over the DataGrid control.

The GridView control uses the assigned data source to edit the data records and the developer will have to add an additional query to the SqlDataSource control for updation of data. The code would be something like the one illustrated below.

updateCommand="UPDATE StudentMaster SET StudentName=@StudentName, StudentAge=@StudentAge WHERE(StudentMaster.StudentID=@StudentId)"

When the AutoGenerateEditButton property is set to true, the GridView displays an additional column. When update is clicked the GridView searches for an appropriate command object on the underlying data source. It fires the rowUpdating event and checks the CanUpdate property of the data source.

Deleting Displayed Records

Deleting records is similar to updating and Editing. The GridView rides on the data source’s ability to perform data operations. The record deletion is enabled by specifying the AutoGenerateDeleteButton to True. The GridView then renders a column of Delete buttons for each row on the GridView. The data source method is passed as a dictionary key filed name/value pair to uniquely identify the row to delete. However, the GridView does not provide any feedback on the operation.

Inserting Records

GridView does not support inserting data against a data source object.

Using Templates

Individual templates can be defined for each field.

Assigning data binding to a control within a template is easy. Besides individually created fields, the GridView control offers two integrated Templates, PageTemplate and NullTemplate. The latter is useful when an assigned data source returns an empty list of data records. A message can be flashed to the user if an empty record set is returned.

The GridView indeed comes with a lot of goodies. Developers are freed from the large volume of code that had to be written. Though the look and feel of the GridView is similar to the DataGrid, it is really very different.

In the next section we shall examine the DetailsView which is a complementary to the GridView in several ways.

 

 

{mospagebreak title=ASP.NET 2.0 – GridView Control Data}

To test the page 1. Switch to Open the Default.aspx page, and then press CTRL+F5 to run the page.

2. The GridView control is displayed with StudentId, StudentName, StudentAge, and CourseId columns. Click a column heading to sort by the contents of that column.

Editing the GridView Control Data

The GridView control already contains all the functions necessary for editing data, since the control is abstract and generic. In fact this is the greatest strength of the GridView control over the DataGrid control.

The GridView control uses the assigned data source to edit the data records and the developer will have to add an additional query to the SqlDataSource control for updation of data. The code would be something like the one illustrated below.

updateCommand="UPDATE StudentMaster SET StudentName=@StudentName, StudentAge=@StudentAge WHERE(StudentMaster.StudentID=@StudentId)"

When the AutoGenerateEditButton property is set to true, the GridView displays an additional column. When update is clicked the GridView searches for an appropriate command object on the underlying data source. It fires the rowUpdating event and checks the CanUpdate property of the data source.

Deleting Displayed Records
Deleting records is similar to updating and Editing. The GridView rides on the data source’s ability to perform data operations. The record deletion is enabled by specifying the AutoGenerateDeleteButton to True. The GridView then renders a column of Delete buttons for each row on the GridView. The data source method is passed as a dictionary key filed name/value pair to uniquely identify the row to delete. However, the GridView does not provide any feedback on the operation.

Inserting Records
GridView does not support inserting data against a data source object.

Using Templates
Individual templates can be defined for each field.

Assigning data binding to a control within a template is easy. Besides individually created fields, the GridView control offers two integrated Templates, PageTemplate and NullTemplate. The latter is useful when an assigned data source returns an empty list of data records. A message can be flashed to the user if an empty record set is returned.

The GridView indeed comes with a lot of goodies. Developers are freed from the large volume of code that had to be written. Though the look and feel of the GridView is similar to the DataGrid, it is really very different.

In the next section we shall examine the DetailsView which is a complementary to the GridView in several ways.

« « ASP.NET GridView Filtering
ASP.NET Using a Grid to Display Detail Information » »

Author Description

Avatar

Editorial Team at Exforsys is a team of IT Consulting and Training team led by Chandra Vennapoosa.

Free Training

RSSSubscribe 394 Followers
  • Popular
  • Recent
  • What’s New in the .NET Framework 2.0 ?

    July 26, 2005 - 0 Comment
  • Forms Authentication in ASP.NET

    September 2, 2005 - 0 Comment
  • ASP.NET Page Object Model

    August 14, 2005 - 0 Comment
  • ASP.NET Displaying Master-Detail Data on the Same Page

    September 13, 2005 - 0 Comment
  • ASP.NET Working with Web Parts

    August 22, 2005 - 0 Comment
  • ASP.NET Managing Membership and Roles

    August 6, 2005 - 0 Comment
  • ASP.NET Server Controls

    August 15, 2005 - 0 Comment
  • Displaying Master-Detail Data on Separate Pages in ASP.NET

    September 16, 2005 - 0 Comment
  • ASP.NET Using Web Parts and Controls in Web Pages

    August 22, 2005 - 0 Comment
  • ASP.NET Configuring Page-Level Caching

    August 30, 2005 - 0 Comment
  • Application Development in .NET

    November 21, 2007 - 0 Comment
  • ASP.NET Advanced Site Functionality

    September 16, 2005 - 0 Comment
  • ASP.NET : Dynamic Image control

    September 16, 2005 - 0 Comment
  • ASP.NET Creating Web Wizards

    September 16, 2005 - 0 Comment
  • Displaying Master-Detail Data on Separate Pages in ASP.NET

    September 16, 2005 - 0 Comment
  • ASP.NET Displaying Master-Detail Data on the Same Page

    September 13, 2005 - 0 Comment
  • ASP.NET DataBound Controls – Details View

    September 13, 2005 - 0 Comment
  • ASP.NET Using a Grid to Display Detail Information

    September 13, 2005 - 0 Comment
  • ASP.NET GridView Filtering

    September 10, 2005 - 0 Comment
  • ASP.NET GridView Control

    September 10, 2005 - 0 Comment

Exforsys e-Newsletter

ebook
 

Related Articles

  • Application Development in .NET
  • ASP.NET Advanced Site Functionality
  • ASP.NET : Dynamic Image control
  • ASP.NET Creating Web Wizards
  • Displaying Master-Detail Data on Separate Pages in ASP.NET

Latest Articles

  • Project Management Techniques
  • Product Development Best Practices
  • Importance of Quality Data Management
  • How to Maximize Quality Assurance
  • Utilizing Effective Quality Assurance Strategies
  • Sitemap
  • Privacy Policy
  • DMCA
  • Trademark Information
  • Contact Us
© 2023. All Rights Reserved.IT Training and Consulting
This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish.AcceptReject Read More
Privacy & Cookies Policy

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.
Non-necessary
Any cookies that may not be particularly necessary for the website to function and is used specifically to collect user personal data via analytics, ads, other embedded contents are termed as non-necessary cookies. It is mandatory to procure user consent prior to running these cookies on your website.
SAVE & ACCEPT