OK – remember when you first heard about the DataGrid, and how Paging and Sorting were what was called “built-in”? And then, when you found out what a hassel it was, even though it was a lot better than what you had before, you still were kind of disappointed?
Well – now we have the GridView, in ASP.Net 2.0 and your disappointment is over! The ‘AllowPaging’ and ‘AllowSorting’ properties mean exactly what they say – once you set them to ‘True’ – that’s it – that’s all you need to do. It’s what we were all wishing for with the DataGrid.
But wait – there’s more (I hope this doesn’t sound too much like an infomercial)! With only one other control on the page, you can display data quickly and efficiently and never write a line of code to bind to the GridView. That control is the DataSource control. (You can find out more about how to use it here). Add a DataSource control to the page, assign the desired values to the properties both it and the Gridview and you’re through. No more forgetting the Sorting Sub or the Paging Sub or forgetting that you need a DataSet – not a DataReader, in able to add sorting and paging to the grid.
I know – you might be saying to yourself “That can’t be correct!”, but I assure you, it is. Here’s all you need to display data from your favorite Database table:
<asp:GridView id="MyGridView" DataSourceID="MyDataSource1" Runat="Server"/> <asp:SqlDataSource ID="MyDataSource1" runat="server" ConnectionString="Server=YourServer;uid=YourUID;pwd=YourPWD;database=YourDB" ProviderName="System.Data.SqlClient" SelectCommand="SELECT [Field Name List] FROM [Table Name]"> </asp:SqlDataSource>
Really! – that’s all there is to it! One thing to remember is that the Provider name is apparently case-sensitive, so make aure that’s entered correctly. And – as was noted earlier, to enable Paging and/or Sorting, just add the ‘AllowPaging’ and ‘AllowSorting’ properties to the GridView:
<asp:GridView id="MyGridView" DataSourceID="MyDataSource1" AllowSorting="True" AllowPaging="True" Runat="Server"/>
Naturally, there are many more features/attributes to the GridView, much like the DataGrid, including all the formatting options you might need. And, you’re probably saying – “Yea – but what about updating/editing?”. Well, that’s gotten a lot easier also. Just a few things to add.
- Enter an Updatecommand (Update SQL Statement) to the existing DataSource, just as you added a SelectCommand.
- Add two properties to your GridView (AutoGenerateEditButton and DataKeysNames)
So – here’s what’s needed in the changed Controls (using Pubs as an example):
Continues…
Great guide, thanks so much!