DataGrid Code

Need to get a DataGrid up on the fly? Here’s some code from Justin Cook’s Behold the Power of the DataGrid!. Here you’ll find the code on making a grid, how controlling the way it looks, and a sorting technique.

Getting a DataGrid up and running:

[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]

DataGrid Looks

[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.

Sorting

[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.

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