We’ve come SUCH a long way since the DataGrid, and even though the DataGrid, at the time was better than what we had before, now there’s the GridView – what we all wished the DataGrid had always been!
When MS says Paging and Sorting is built in – this time, they really mean it. What you see in this sample is two declarative controls on the page – that’s all – no code whatsoever.
Also look at the way you can control which columns get sorting capabilities. To keep any column(s) from being sorted, just leave out the SortExpression property in the BoundField for that column – that’s all there is to it!
Also notice, that for each column, the second time you click on the header link text, the order changes (back and forth between Ascending and Descending), with no extra code.
<html> <head> <meta name="GENERATOR" Content="ASP Express 4.5"> <title>Paging and Sorting With a GridView</title> </head> <body> <form id="form1" Runat="server"> <div align="center"> <asp:Label ID="label1" ForeColor="Blue" Font-Bold="True" Runat="server" /> <asp:GridView Runat="server" Id="gvPublishers" GridLines="Both" cellpadding="0" cellspacing="0" Headerstyle-BackColor="#BDCFE7" Headerstyle-Font-Name="Arial" Headerstyle-Font-Size="12" BackColor="#E7EFFF" Font-Name="Arial" Font-Size="10" BorderColor="Black" DataSourceID="SQLDS1" AllowPaging="True" AllowSorting="True" AutogenerateColumns="False"> <Columns> <asp:BoundField DataField="CustomerID" SortExpression="CustomerID" ItemStyle-HorizontalAlign="Center" HeaderText="ID"> </asp:BoundField> <asp:BoundField DataField="CompanyName" SortExpression="CompanyName" ItemStyle-HorizontalAlign="Center" HeaderText="Company"> </asp:BoundField> <asp:BoundField DataField="ContactName" SortExpression="ContactName" ItemStyle-HorizontalAlign="Center" HeaderText="Contact"> </asp:BoundField> <asp:BoundField DataField="City" SortExpression="City" ItemStyle-HorizontalAlign="Center" HeaderText="City"> </asp:BoundField> <asp:BoundField DataField="PostalCode" ItemStyle-HorizontalAlign="Center" HeaderText="Postal Code"> </asp:BoundField> </Columns> </asp:GridView> </div> <asp:SQLDataSource ID="SQLDS1" ConnectionString="<%$ ConnectionStrings:YourConnStringGoesHere %>" ProviderName="System.Data.SqlClient" SelectCommand="Select (FieldList) from Customers" Runat="Server"> </asp:SQLDataSource> </form> </body> </html>