Introduction

This article provides an approach to building an application that may be used to collect, store, and retrieve data without relying upon a database to get there. If you need to store a limited amount of data, if your users won't be sharing data with other users, and you do not require a full blown relational database on the backend, this article might be of interest.

The article is built around a demonstration project that allows the user to store some information gathered during bird observation; of course the same approach could be used to work with contact information, an inventory, postage stamp collection, coin collections, movie collections, or whatever else you might be interested in keeping tabs on.

Figure 1: Application Main Form.

The application provides the following functionality:

Create a bird data file.

Add birds to the bird data file.

Remove birds from the bird data file.

Search for specific birds by name.

Create and edit details about the bird.

Bird name

Bird gender

Bird location

Bird behavior

Observation date

Observation time

Image of the bird

Save a bird data file.

Reopen a bird data file.

Navigate through all of the birds in the bird data file.

View a list of all birds in the bird data file.

The approaches used within the application are representative of only one way of doing things. As with most things in the .NET world, there are several alternatives and you can modify the code to work with the data using one of the other alternatives if you prefer to do so.

Figure 2: Finding a Bird.

Figure 3: Listing All Birds.

Getting Started

There is a single solution included with this download, the solution contains a WinForms project called BirdWatch_VB; this project contains three forms (the main form, a search form, and a form used to display the total list of birds), a serializable class called BirdData.vb (used to contain bird related data), and a class entitled FileSerializer.vb which contains two staticmethods used to serialize and deserialize the bird data (writing it to and reading it from a file) .

If you open the attached project into Visual Studio 2008; you should see the following in the solution explorer:

Figure 4: Solution Explorer.

Code: BirdData.vb

The BirdData class is the container class used to store all of the bird related data used in the application. Whilst this demonstration uses bird data, this could easily be replaced with something more useful to you.

The next region of code in the class contains the constructors. Two constructors are defined; a default constructor that creates a new instance of the class and assigns it an internal ID (as a Guid). The second constructor accepts a bird name as an argument and, when called, this constructor generates both an ID and assigns the bird name property to the bird name member variable.

The last bit of the code in this class is contained within the properties region; this region contains all of the properties defined to access the member variables. Note that since the ID value is always set by the constructor, the property does not provide a publicinterface to set the Guid to a new value.

'''<spanclass="code-SummaryComment"><summary></span>''' A simple project used to maintain data about a
''' collection of birds (could be anything), and to
''' display that data to the user, persist the data,
''' and allow the user to recover and modify the
''' data without using a database.
'''<spanclass="code-SummaryComment"></summary></span>PublicClass Form1

The region defined in the class declares the member variables used internally by the class; any member variables exposed externally are made accessible through publicproperties. The comment adjacent to each declaration describes its purpose.

#Region"Variable Declarations"Private birds As List(Of BirdData) ' a container for the bird collection
Private currentBird As BirdData ' the current bird (displayed)
Private currentFilePath AsString' the path to the bird data file
Private currentPosition AsInteger' the position within the bird list
Private dirtyForm AsBoolean' mark the form dirty when changed
#End Region

The next region of code in the class contains the constructor. Upon initialization, the application creates a new bird data list, creates a new bird data object, sets the date and time picker controls to the current data, sets the current position indicator to zero, and sets the dirty form Booleanto false.

The next code region is called Housekeeping. This region contains some basic functionality used to operate the application. The first code section is for the Exit toolbar button click event handler; this function merely calls the exit menu item option’s event handler rather than duplicate the code in both functions.

The next section of code is the exit menu option’s click event handler. This code first checks to see if the form is marked as dirty (based upon user changes made during the operation of the application); if the form is dirty and the user attempts to exit the application, users will be presented with a message box which will ask them whether or not they wish to exit the application without saving. If users indicate that they would prefer to save prior to exiting the application, the application will present the save file dialog to the user; otherwise the application will exit.

The next function contained in the form is used to set the image associated with the current bird. Since we are adding new data to the current instance of bird data, the form is marked as dirty – this will allow the functions used to exit the application to check to see if the current data needs to be saved prior to exiting the application. The function uses the open file dialog to allow the user to set a path to an image file; once a file path is set; the function opens the file, converts it into a byte array and stores it in the current bird data object’s image property. The function wraps up by setting the form’s image to display selected bird picture.

The next function is used to handle the ‘New’ menu option’s click event; this function begins by checking the dirty form Booleanto see if the current data should be saved prior to starting the new bird data file. If the current form is dirty; the user will be prompted to save the current data, else, a new collection of bird data is created and the form is cleared all of prior entries.

The open file menu option’s click event handler is next; this function also checks for a dirty form prior to opening a new bird data file into the application. If the form is not dirty, the application will call the Open function which will in turn allow the user to navigate to and open a file for viewing or edit.

Next, the open method uses the open file dialog control to allow the user to navigate to and select a bird data file. Once selected, the file is deserialized into the local bird collection and made available to the display.

The save menu option click event handler is up next. This function uses the save file dialog to allow the user to name or set the path to the file. Once the file path is set, the application serializes the data contained in the bird collection, saving it to disk.

The save current bird function is used to set the values of the current bird data object to match the content from the form controls.

'''<spanclass="code-SummaryComment"><summary></span>''' Set the current bird values to the form content
''' if the user navigates off the current bird, it will
''' save the content
'''<spanclass="code-SummaryComment"></summary></span>PrivateSub SaveCurrentBird()
IfNotString.IsNullOrEmpty(txtBirdName.Text) ThenTry
currentBird.BirdName = txtBirdName.Text
currentBird.Location = txtLocation.Text
currentBird.BehaviorObserved = txtBehavior.Text
currentBird.Gender = cboGender.Text
currentBird.DateViewed = dtpDate.Value
currentBird.TimeViewed = dtpTime.Value
' bird image byte array is set for current
' bird when image is set
Catch ex As Exception
MessageBox.Show(ex.Message, "Error")
EndTryEndIfEndSub#End Region

The next region is called Bird Data Management; within this section are the methods used to manage the bird data and the bird data collection. The first function contained in this region is used to add a new bird to the collection. The function saves the current bird, creates a new empty bird object, adds the new bird data object to the birds collection, and then marks the form as dirty.

The next function is used to support finding a specific bird. When the click event handler is executed, a new instance of the find form (Form3) is created and an event handler for the find form’s BirdNameUpdated event is set.

The next function is used to find a specific bird by its name. When find form raises the event indicating that the user wants the bird of a particular name found in the collection, this function will iterate through the collection until the match is found and then it will make that bird the current bird and update the form to display that bird’s information.

The next function is used to display a form containing all of the birds contained in the current bird data list. Form2 contains a single data grid view control and it accepts a list of bird data as an argument for the constructor. When the form is created and passed a copy of the current bird data, that data is bound to the data grid view control and displayed to the user.

The next region contained within this class contains two functions used to control navigation forwards and backwards through the bird data list. In either case, the current bird is saved by calling the SaveCurrentBird function. After the current bird is saved locally, the position is checked to see if it is at the bottom or top limit and if possible, the position is incremented or decremented. Once the current position is updated, the current bird data is set to the bird data at the updated position and for the form reloaded.

The last region of code in this class is used to mark the form as dirty in response to changes. Note that, rather than using the value changed events to set the form dirty, other events such as the text box control’s key press event were used to provide an indication as to whether or not something was changed. The reason being that, if one were to open a bird data file and navigate through the list, the values would change and the form would be marked as dirty even though in reality no changes took place.

That wraps up the discussion of the code contained in the main form of the application.

Code: List All Birds Form (Form2.vb)

The form used to display the entire list of birds contained in the current bird data list is pretty simple. The form contains a single data grid view control which is used to display the bird data list. The constructor was modified to accept a bird data list as an argument; the constructor binds the data grid view control to the bird data list and hides the first column (containing a Guid used to uniquely identify the record).

Code: Find Birds Form (Form3.vb)

This form is used to provide the user with a list of the names of all of the birds contained in the current bird data list. The user can view and select bird names from the list and then click on the form’s Find button; this will raise an event which will be used by the main form to load the matching bird into the form.

The class begins with the normal and default library imports, namespace declaration, and class declaration:

Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Linq
Imports System.Text
Imports System.Windows.Forms
'''<spanclass="code-SummaryComment"><summary></span>''' This form class displays a list of existing
''' bird names for the user to pick from; once
''' selected, an event will be raised with
''' the selected bird name passed as an
''' argument. The main form will listen
''' for an process this event to update
''' the display of the current bird to match
''' the search bird.
'''<spanclass="code-SummaryComment"></summary></span>PublicClass Form3

Following the class declaration, a delegate and event are declared; these are used to notify the main form whenever the user selects a bird from the form’s list and then clicks the form’s Find button. The BirdNameUpdateEventArgs is declared as a separate class; that class will be used to contain the selected bird name and to make that information available to the main form whenever the eventis raised.

' add a delegate
PublicDelegateSub BirdNameUpdateHandler(ByVal sender AsObject, ByVal e As
BirdNameUpdateEventArgs)
' and associated event to notify
' listeners when a bird name is
' picked from this form's bird
' name list
PublicEvent BirdNameUpdated As BirdNameUpdateHandler

The constructor was modified to accept a bird data list as an argument; whenever an instance of the form is created, the constructor will iterate through the bird data list and add each bird name to the listbox control used to display the bird names.

'''<spanclass="code-SummaryComment"><summary></span>''' Pass current bird data list to the
''' constructor so that the form can
''' generate a list of bird names for
''' the user to choose from
'''<spanclass="code-SummaryComment"></summary></span>'''<spanclass="code-SummaryComment"><paramname="bd"></param></span>'''<spanclass="code-SummaryComment"><remarks></remarks></span>PublicSubNew(ByVal bd As List(Of BirdData))
InitializeComponent()
' iterate the bird data to add
' each bird name to the bird
' name list box control
ForEach bird As BirdData In bd
listBox1.Items.Add(bird.BirdName)
NextEndSub

The find button click event handler creates an instance of the eventarguments and adds the listbox control’s selected item to the event arguments. Once set, the eventis raised and raising the eventwill force the main form to load the selected bird’s information into the form’s controls.

'''<spanclass="code-SummaryComment"><summary></span>''' When the user clicks on the find button,
''' raise an event so the main form will display
''' the appropriate bird
'''<spanclass="code-SummaryComment"></summary></span>'''<spanclass="code-SummaryComment"><paramname="sender"></param></span>'''<spanclass="code-SummaryComment"><paramname="e"></param></span>'''<spanclass="code-SummaryComment"><remarks></remarks></span>PrivateSub btnFind_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles btnFind.Click
' populate the argument list with the bird name
Dim args AsNew BirdNameUpdateEventArgs(listBox1.SelectedItem.ToString())
' raise the event to pass the bird name back to the
' main form for processing
RaiseEvent BirdNameUpdated(Me, args)
EndSub

The BirdNameUpdateEventArgs class is used to contain the bird name and to facilitate passing the bird name to the main form whenever the bird name updated event is fired. This class could be expanded to contain greater numbers of properties.

Summary

The article shows one approach that may be used to persist and manage data within a WinForms application without actually backing the application with a database. Such an approach might be useful in a number of different applications where the user does not share information with other users. Even though the example shows the approach used to manage a collection of information regarding birds, it could be used for any number of other purposes such as maintaining a library of fly patterns, or your favorite insect collection, inventories of tools or equipment, etc.

I know this article is a little old, but wanted to provide some feedback.

Overall I thought the article was fairly well written. However, the premise of the article does not appear to have been met. The summary states that this is about providing a different method of persisting data besides using a database - and while it is obvious from reading that a file is saved in some format using serialize/deserialize code, it does not explain anything about the format of the data being saved, etc.

I think that the implied intent of this article could have been better served by showing less detail about some of the standard features of any form that opens and saves files, and more detail on the specific solution used to store said data.

I can aways look in the source, but would prefer a little more tangible information as to the solution presented in the article itself.

To be complete, this sample still needs a SORT feature. Newly added birds are always at the end - it might make more sense if they would be sorted alphabetically or if other sorting options would exist.