Home > Articles > Programming > Windows Programming

  • Print
  • + Share This
From the author of

Custom Classes Code Examples

As usual, I take a look at some code samples, both from the server side and from the client side. First, here's some from the server side. In Listing 3, you find some code for using a DataReader to add the data to the custom classes.

Listing 3: Code for Filling the Custom Classes

Dim aDataReader As SqlDataReader = DbHelper.FetchOrderAndLines(id)

Dim anOrder As New Order()
anOrder.Id = aDataReader.GetInt32(OrderColumns.Id)
anOrder.CustomerId = aDataReader.GetInt32(OrderColumns.CustomerId)
anOrder.OrderDate = aDataReader.GetDateTime(OrderColumns.OrderDate)

While aDataReader.Read
  Dim anOrderLine As New OrderLine()
  anOrderLine.ProductId = _[ccc]
  anOrderLine.PriceForEach = _[ccc]
  anOrderLine.NoOfItems = _[ccc]
  anOrderLine.Comment = _[ccc]
End While

Return anOrder


The code for DbHelper.FetchOrderAndLines() was actually shown in the first article in this series. See Listing 1 in that article.

If you have worked with the DataReader at all, I think you'll find the code in Listing 3 quite simple. Worth mentioning is that, in this case, I know that there will only be one row (one order) in the first resultset, so I have no loop. Then I have a loop for the second resultset so that I can grab all the order lines. As you see, I use enums to address the correct columns in the DataReader.


Now for a note that is a bit off-topic but still interesting: I always use Option Strict for my VB.NET projects. Therefore, it came as a surprise to me when I found out that the equivalent C# code to the VB.NET code shown in Listing 3 won't work directly. When using C#, the enum values must be cast to int when used in the GetInt32() function, for example. That is not needed for VB.NET.

Now, as usual, for some code from the client side. To browse the information in the custom classes, the code could look like it does in Listing 4.

Listing 4: Code for Browsing a Wrapped DataSet

Dim anOrder As Order = _service.FetchOrderAndLines(_GetRandomId())

_id = anOrder.Id
_customerId = anOrder.CustomerId
_orderDate = anOrder.OrderDate

Dim anOrderLine As OrderLine
For Each anOrderLine In anOrder.OrderLines
  _productId = anOrderLine.ProductId
  _priceForEach = anOrderLine.PriceForEach
  _noOfItems = anOrderLine.NoOfItems
  _comment = anOrderLine.Comment

In Listing 4, you find the smallest amount of client-side code shown in all the articles—and it's the clearest, too. I think I've said it before, but I think it's a great deal to buy a simple API for the client programmer and to pay with some more server-side code.

  • + Share This
  • 🔖 Save To Your Account