Behold the Power of the DataGrid!

This article will convince you that it truly is time to make the switch over to .NET. I will explain how one component could simplify our programming lives to a hardly fathomable extent. Microsoft has put a lot of thought into this RAD approach to hooking our applications to a database, delivering to us the DataGrid. I will explain how to use a DataGrid in its naked form, as well as with some formatting, and finally how to sort the data.

Introduction

As I was studying and learning about these new-fangled components introduced by ASP.NET called Server Controls, it was as if things just kept getting better and better. Seriously, I am the type to give credit where credit is due, and I just have to say “well done” to MS on this one. You see, the HTML and Validation controls are pretty cool. The state-full behavior of a Web control is really cool. Then I got to the data-bound controls — they are extremely cool.

I was thrown back in time to the first inventory application I worked on. If only I had the option of using .NET, I could have saved so much time! So many repetitious and tedious lines of ASP code to provide both simple and advanced functions, all of which are encapsulated in these pre-built controls. A few simple lines give us options that are anything but simple.

Of all the server controls, the most impressive to me was the DataGrid. Although it belongs in the data-bound controls family, I must say that it blows away the Repeater or DataList controls in power and versatility. While those two have their uses, I am going to concentrate on the usefulness of the DataGrid in this article, and I’m going to have to do two articles to even do it justice! Hmm, my wife says that I have a tendency to build things like movies up way too much, and then they’re not as great as I made them sound (UHF for one). So, at risk of building this up too much, let’s just get to the point!

{mospagebreak title=What on Earth is a DataGrid?}

Ok, how do I best explain this? All right, a common use of server-side programming is to retrieve data from a database and display it on a web page. You can then do additional things with the displayed data, such as give the users the option of adding one or more of the items to a shopping cart, perhaps giving moderators the ability to modify individual chucks of that data. Then, as you get more data, you’ll want to add advanced features, like displaying incremental portions of the data, referred to as paging.

Now all of these things can be accomplished with plain old ASP, and you’ll find lots of help on ASP Free if that’s what you want to do. But trust me, for every extra option you want, you’ve got approximately 1.5 million lines of code to type out (maybe a slight exaggeration). Then you have to go back and debug your improperly displayed tables. Then you have to add in client-side JavaScript to accomplish something fancy, then debug that! Then if you need to reuse the functionality in another page or application, there’s usually a good deal of time wasted on figuring out where to copy and modify your code, then of course more debugging time.

If you’re thinking I have a chip on my shoulder here, you may be justified with such thoughts. This is only the case however, since I learned of an infinitely better way of doing it all. I was quite happy to whittle away the hours before, but now that Microsoft has taken such huge steps towards Rapid Application Development, I’m quite happy to change with the times.

With ASP.NET, Microsoft realized that thousands of people are trying to do the very same or similar things in their ASP applications, so why not give them a much better way to do it? And thus is born the DataGrid. We can ‘bind’ the DataGrid to a dataset, and have it spit it all out in tabular format in a very automated fashion. We can easily configure advanced options like sorting and paging, by merely configuring a few attributes of the DataGrid.

Excited yet? It’s OK, you don’t have to hide your excitement, you don’t have to be worried about being called a geek. We all are, that’s why we’re here!  Throughout the following articles, we will discuss the various options of a DataGrid, including:

  • Data binding
  • Configuring display
  • Alternate row styling
  • Sorting
  • Paging
  • Selecting
  • Updating

{mospagebreak title=Data Binding}

To get the DataGrid up and running, all we really need is a valid data source. By default, the DataGrid control will take the data, and spew out an exact representation in tabular format. Each record will be displayed in a unique row, and each field will have its own unique column. This can be accomplished in as little as three lines of code. For this example and the rest, I will omit the actual coding used to populate the dataset, which I’ll show in the final example of the second article. Really the only omitted code is the data retrieval, which you should be familiar with by now after reading the ASP.NET basics on ASP Free.

[code]
<script language=”VB” runat=”server”>

 

‘=== omitted code use to fill a dataset called dsInventory

 

‘=== databind to DataGrid called dgSocks
dgSocks.DataSource = dsInventory.Tables(“socks”)
dgSocks.DataBind()
</script>
<asp:DataGrid id=”dgSocks” runat=”server” />
[/code]

Believe it or not, it’s really that simple! We now have an automatically generated table (or grid) displaying all the data in the socks data table! Ooooh, the power. But now let’s get into a bit of customization.

How Do I Look?

The first thing we’ve got to do is tell .NET to back off a little, because we want to get our hands a little dirty here. We do that by setting the AutoGenerateColumns to false. Then we get to work deciding in which order to display the columns, how we want them formatted, and even details such as the header appearance.

We need to work with a number of properties here for the sake of this tutorial; you can implement some or all of them as you see fit. We configure each desired column in the chosen order, by using sequential <BoundColumn> objects. We can go deeper, by adding and modifying properties within each <BoundColumn>, by using the <ItemStyle> property. The <HeaderStyle> and <AlternatingItemStyle> properties can be employed to change the grid header and the alternate row styles respectively.  Here’s the code:

[code]
<script language=”VB” runat=”server”>

 

‘=== omitted code use to fill a dataset called dsInventory

 

‘=== databind to DataGrid called dgSocks
dgSocks.DataSource = dsInventory.Tables(“socks”)
dgSocks.DataBind()
</script>
<asp:DataGrid id=”dgSocks” runat=”server” AutoGenerateColumns=”false”
width=”400″ cellPadding=”2″ Font-Size=”10px”>
 <HeaderStyle BackColor=”Salmon” Font-Bold=”true” />
 <Columns>
  <asp:BoundColumn HeaderText=”Sock Color” DataField=”color” />
  <asp:BoundColumn HeaderText=”Price” DataField=”price”>
   <ItemStyle HorizontalAlign=”right” />
  </asp:BoundColumn>
 <Columns>
 <AlternatingItemStyle BackColor=”#CCCCCC” />
</asp:DataGrid>
[/code]

If you want to get really fancy, you could even add DataFormatString=”{0:c}” to the price to print it out in currency format! If you want more information on that, Microsoft has all the answers. But enough with styling, you can play around with that, let’s move on to bigger and better things, namely sorting.

{mospagebreak title=Who Wears Sort Sorts?}

I haven’t the slightest fondness of my memories of sorting. Whether we’re talking about laundry or data, it was a tedious pain in the butt. True, it’s just a matter of requesting the proper ‘SORT BY’ within our SQL statement, but that also involves a lot of client and server scripting to pick up and remember exactly how the user wanted the data sorted. Well, no more I tell you, no more!

Just a side point here: we could use a DataView object to sort the data, and then bind the DataGrid to that. However, since we’re talking about revamping the whole SQL ‘SORT BY’ method, that’s the approach this tutorial will cover.

Ok, we need to now establish that in order to sort this grid, we’re basically going to re-populate the dataset on each sort request, just in a different order. When the page is loaded the first time, the dataset will be sorted in a default manner, by the sock ID.

Really, all we need to is set the AllowSorting property of the DataGrid to be true, and tell it what to do when it receives an OnSortCommand. We can basically re-set up the initial data-binding subroutine to now pick up a sort value, passed by whichever column is clicked on to sort by, and re-populate the DataGrid! Here’s the code:

[code]
<script language=”VB” runat=”server”>
Sub doBinding( optional sortBy As String “id” )
 ‘=== omitted code use to fill a dataset called dsInventory

 

 ‘=== databind to DataGrid called dgSocks
 dgSocks.DataSource = dsInventory.Tables(“socks”)
 dgSocks.DataBind()
End Sub

Sub reSort( s as Object, e As DataGridSortCommandEventArgs )
 doBinding( e.sortExpression )
End Sub
</script>
<asp:DataGrid id=”dgSocks” runat=”server” AutoGenerateColumns=”false”
 width=”400″ cellPadding=”2″ Font-Size=”10px”
 AllowSorting=”true” OnSortCommand=”reSort”>
 <HeaderStyle BackColor=”Salmon” Font-Bold=”true” />
 <Columns>
  <asp:BoundColumn HeaderText=”Sock Color” DataField=”color” />
  <asp:BoundColumn HeaderText=”Price” DataField=”price”>
   <ItemStyle HorizontalAlign=”right” />
  </asp:BoundColumn>
 <Columns>
 <AlternatingItemStyle BackColor=”#CCCCCC” />
</asp:DataGrid>
[/code]

So, there’s nothing too cryptic about this. When we click on the column to sort the data, the column name is passed back to the doBinding subroutine via the reSort subroutine. Like I said, the default is the ID of the socks. Within our actual SQL statement, we always include the sortBy variable (“SELECT * FROM socks ORDER BY ” & sortBy), and that way we don’t have to worry if we haven’t specified a sort column, the default “id” will be used.  By the way, the default here is to sort in an ascending fashion.

Now are you beginning to see the incredible power of the DataGrid? This is only the tip of the proverbial iceberg! Just wait until the next installment; your trepidation to migrate to .NET will be out the window.

Conclusion

I have introduced you to my new friend the DataGrid. You’ve started to learn a few of his qualities, his attributes, but the best is yet to come.  The next time around we’re going to find out how a DataGrid provides so graciously for our paging and editing requirements. I recommend that in the meantime you get comfortable binding data to a DataGrid, and spit out lots of tables.

It has been said that absolute power corrupts absolutely. Well, whether or not you choose to be corrupted by the DataGrid is entirely your prerogative, but I still wholeheartedly support this little powerhouse. May you employ the DataGrid gratuitously throughout your programming life, and may your applications live long and prosper!

[gp-comments width="770" linklove="off" ]