Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

Sorting a gridview that uses sqldatasource control - Part 44

Suggested Videos 
Part 41 - Detailsview insert update delete using objectdatasource control
Part 42 - Detailsview insert update delete without using data source controls
Part 43 - Nested gridview in ASP.NET



In this video we will discuss about sorting a gridview control that use sqldatasource control. We will discuss about sorting in both ascending and descending order.

We will be using tblEmployee table for this demo. Please refer to Part 13 by clicking here, if you need the sql script to create and populate these tables.



Step 1: Drag and drop a gridview and a sqldatasource control on webform1.aspx

Step 2: Configure SqlDataSource1 control to retrieve data from tblEmployee table.

Step 3: Associate GridView1, with SqlDataSource1 control and make sure to select "Enable Sorting" checkbox.
asp.net gridview sort

That's it we are done. Run the application. Click on any column to sort the data. Notice that, when you click once on the column header, the data will be sorted in ascending order, and if you click again the data will be sorted in descending order. A gridview that is sortable in both directions is called as bi-directional sortable gridview.

Points to remember
1. When sorting is enabled, AllowSorting attribute of GridView1 is set to true.
AllowSorting="True"
2. If you don't want to sort on a specific column, remove SortExpression attribute from that column

Here is the HTML
<asp:GridView ID="GridView1" runat="server" AllowSorting="True" 
    AutoGenerateColumns="False" DataKeyNames="EmployeeId" 
    DataSourceID="SqlDataSource1">
    <Columns>
        <asp:BoundField DataField="EmployeeId" HeaderText="EmployeeId" 
            InsertVisible="False" ReadOnly="True" SortExpression="EmployeeId" />
        <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
        <asp:BoundField DataField="Gender" HeaderText="Gender" 
            SortExpression="Gender" />
        <asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />
    </Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
    ConnectionString="<%$ ConnectionStrings:SampleConnectionString %>" 
    SelectCommand="SELECT * FROM [tblEmployee]">
</asp:SqlDataSource>

No comments:

Post a Comment

It would be great if you can help share these free resources