I wrote a short piece for Personal Computer World about making a simple Windows Forms database application. I did this because I get a lot of enquiries about it, and search hits to this site looking for samples.
The piece is actually in two parts. Part one shows how to do CRUD without any databinding or datasets.
Part two is about using the VB wizards to create an app with a typed dataset, TableAdapters and so on. The database is SQL Server CE, which is well suited to this kind of application. It is the default in Visual Studio 2008 even though it turns out not to be fully compatible with the wizards. Typical Microsoft – simple, but with enough gotchas to frustrate beginners and keep experts in business.
I ran into another little puzzle while doing the sample. I needed to populate the listbox with both a string value and the ID that is the primary key in the database table. The way I would do this normally is to create a custom class to represent the record, implement a ToString() that returns the display value, and add instances of this object to the listbox. I wanted an even simpler way though, so I decided to use a ListView. This lets you add items that have both a key and a value. You can do this with one of the overloaded Add methods for a ListViewItemCollection, documented like this:
Creates an item with the specified key, text, and image and adds an item to the collection.
The strange thing is, the ListViewItem has no key property. So how do you retrieve the value of the key?
The answer is that the ListViewItem.Name property returns the value of the key. So the key is the name. Why not call it the name in both places? Or the key?
I guess that would be too easy.