You are on page 1of 27

ADO.NET Data Form Wizard In VB.

NET

You can use the Data Form Wizard to develop your database application with viewing, updating, and deleting
capabilities. This is probably the fastest way to develop database applications in .NET .

In this article, you'll use a Data Form Wizard to write a fully functioning database application including features
such as inserting, updating, and deleting data without writing including features such as inserting, updating,
and deleting data without writing a single line of code. In this simple example, I've used the familiar Northwind
database. I'll use both the Customers and Orders tables to show you data relationship  between table data.

Like Many parts of this article, this topic is in the form of tutorial. Just follow the simple steps, and in a few
minutes you'll be able to run a wonderful application. In this article, you're going to create a windows
application. After that you'll add a Data Form Wizard to it and call the Data Form Wizard from the main
application.

Step 1: Selecting a Project Template

Create a new windows project by selecting New project > Visual Basic projects > windows application and
typing your application name (see figure 4-56).

Figure 4-56. Creating a windows application project

Step 2: Adding a Data Form Wizard Item


Now add a Data Form Wizard by selecting project > Add New Item > Data Form Wizard from the available
templates. You can type the name of your Data From class in the Name field of the dialog box (see figure 4-57).

Now click Open, which calls the Data Form Wizard.

Step 3: Walking through the Data Form Wizard

The first page of the wizard is a welcome page telling you what the wizard is about to do (see figure 4-58).

Figure 4-58. Welcome page of the Data Form Wizard

Step 4: Choosing the DataSet You Want

On the second page of the wizard, you can choose a dataset name that will later be used to access the data.
You can either create a new dataset name or select an existing one. In this example, I'll choose MyDS as the
dataset name (see in figure 4-59).
Figure 4-59. Choosing a Dataset in the Data Form Wizard

Step 5: Choosing a Data Connection

The next page of the wizard asks you to provide a connection. The combo box displays your available
connection. If you didn't create a connection, use the New Connection button, which launches the server
Explorer discussed earlier in this article. I'll select the usual database, Northwind (see figure 4-60).
Figure 4-60. Choosing a data connection in the Data Form Wizard

Step 6: Choosing Tables or Views

The next page of the wizard lets you pick the table and views you want to connect to the dataset. As you can
see in figure 4-61 select the Customers and Order tables in the Available Items list on this page and use the >
button to add these tables to the selected Items list.
Figure 4-61. Choosing a DataTable or DataView in the Data Form Wizard

Now you're ready to create a relationship between these two tables.

Step 7: Creating a Relationship between Tables

The next page lets you define a relationship between the Customers and Orders tables. It's useful to provide a
relationship between tables when you have a master detail relationship database. In other words, a customer
may have many orders associated with it, so there is a relationship through the Customer ID in the Orders
table joined to information about the customer in the Customers table. Now, say you want to see all the
orders of a customer based on the CustomersID. If you do this manually, you need to write code to select data
from the Orders table to correspond to a CustomerID and then fill data to the form. If you use Data Form
Wizard instead, it does every thing for you. Neat huh?

This is the same step you're going to see on the Create a Relationship between Tables page of the wizard.
You're going to create a relationship between the Customers and Orders table based on the Customer ID. I
named the relationship between Customers and Orders table CustOrderRelation. You also need to pick the
associated primary key and foreign key that links the parent to the child table. Once you've chosen the joining
key (CustomerID), you have to click the >button to tell the wizard that you want to add it.

When you run the final program, you'll see how you can filter all orders for a customer based on the
CustomerID. As you can see from figure 4-62, you need to pick one table as parent and another table as a child
based on the relationship between them. In this example, the Customers table is the parent table, and the
Order table is the child table.

Figure 4-62. Selecting Customers as the parent and Orders as the child table to create the custOrderRelation
relationship

After adding the relationship to the Relations list, the wizard looks to like (figure 4-63).
Figure 4-63. CustOrder Relation listed in the Relations list

Step 8: Choosing Tables and Columns to Display on the Form

The next page of the wizard lets you select which tables and columns you want to show on the form. For this
example, select all the columns from both of the tables (this is the default selecting). As you see in figure 4-64,
the Customers table is the master, and the Orders table is the detail table.
Figure 4-64. Choosing columns to display on the Data From Wizard

Step 9: Choosing the Display Style

This page is an important part of creating your form. Actually The Data Form Wizard adds a Windows form
with some controls on it and writes code to fill, update, delete, and navigate data. There are two ways to view
the data, and you choose your option on this page. These two options are:

 All Records in a Grid


 Single Record in Individual Controls

Figure 4-65. Display these options.


Figure 4-65. Choosing between a grid and individual controls on the Data From wizard

The output of All Records in a Grid looks like Figure 4-66. After that you can resize controls on the form.
Figure 4-66. GridData From output

The second option, Single Record in Individual Controls, shows data text boxes and provides you with
navigation controls. As you can see from figure 4-67, the single Record in Individual Controls option activates
Add, Delete, Cancel, and Navigation controls check boxes. You can uncheck the check boxes if you don't want
to add that feature in your project.
Figure 4-67. The single Record in Individual Controls option

The form generated by this generated by this option looks like figure 4-68. As you can see from figure 4-68,
each column of the table has a field on the form.
Figure 4-68. Data Form Wizard- generated form for the single Record in Individual Control option

After your selection of data display style, you click Finish button. The Data From Wizard adds the windows
form DataFrom1 and the class DataFrom1.cs corresponding to it.

Step 10: Calling the Data Form Wizard Form from the Application

Now you need to change one more thing. You need to call DataFrom1 when you start your application. By
default your application calls the Form1 form on start up.

    Private Shared Sub Main()
        Application.Run(New Form1())
    End Sub

So, you need to replace Form1 with your Data Form Wizard's form name. In this example, listing 4-6 replaces
Form1 with DataFrom1 in the main method.
Listing 4.6 Calling Data From1 from the application

    Private Shared Sub Main()
        Application.Run(New Form1())
    End Sub

NOTE: If you've modified the name of your Data From Wizard-generated form, you need to call that form
instead of Data From1.

Step 11: Viewing the Output

Now you should see the output shown in figure 4-69 when you run your application (if you selected the grid
view option).

The load and Update buttons load and update the data, respectively, and Cancel all cancels all the operations.
The neat thing is if you more into the top grid corresponding information changes in the button grid. Neat,
huh?

Figure 4-69. Data Form Wizard with all records in a grid option
Figure 4-70 shows the output when you select the single Record in Individual Control option. By using this view
option, you can add, edit, delete, and navigate records easily.

Figure 4-70.Textbox Output with navigational controls

Finally, compile and run your application. Without writing a single line of code, you just created a fully
functional database application.

The Load button on the individual control form loads the data, and the Add, Update, and Delete buttons on the
form inserts, updates, and deletes records, respectively.

Data From Wizard: Looking under the Hood


You just saw how you can develop fully functional database applications in no time with the help of the Data
Form Wizard. Now let's see what the wizard does for you in the actual code. (The inherent beauty of VS.NET is
that it magically hides all the messy code for you.) The wizard adds two items to your project: MyDs.xsd and
DataForm1.cs.

Understanding MyDS.xsd

MyDs.xsd is an XML schema for the dataset you've added to the project. It's similar to the one discussed in the
"Understanding Typed DataSets in visual studio .NET" article of this article.

Understanding Data From1.cs

The second item added by the wizard is the DataForm1 class, a class derived from
System.Windows.Forms.Form. The DataForm1 class defines its entire functionally. The InitializeComponent
method creates the data connection, the data command, the data adapter, the dataset, and other data
components.

The LoadDataSet method loads the data from the data source into the controls by calling FillDataSet (see
listing 4-7).

Listing 4-7. Load DataSet method generated by the Data Form Wizard

    Public Sub LoadDataSet()
        ' Create a new dataset to hold the records returned from the call to FillDataSet.
        ' A temporary dataset is used because filling the existing dataset would
        ' require the databindings to be rebound.
        Dim objDataSetTemp As MyDataFormWizardSamp.MyDS
        objDataSetTemp = New MyDataFormWizardSamp.MyDS()

        Try
            ' Attempt to fill the temporary dataset.
            Me.FillDataSet(objDataSetTemp)
        Catch eFillDataSet As System.Exception

            ' Add your error handling code here.


            Throw eFillDataSet
        End Try

        Try
            ' Empty the old records from the dataset.
            objMyDS.Clear()
            ' Merge the records into the main dataset.
            objMyDS.Merge(objDataSetTemp)
        Catch eLoadMerge As System.Exception

            ' Add your error handling code here.


            Throw eLoadMerge
        End Try
    End Sub

FillDataSet fills the dataset from the data adapter by calling the Fill method on each data adapter. Note that
with the Data Form Wizard, a DataAdapter is created for each table, One DataAdapter for The Customers table
and one DataAdapter for the Orders table. Both DataAdapters fill the same DataSet. Listing 4-8 shows the
FillDataSet method.
Listing 4-8. The FillDataSet method generated by the Data Form Wizard

    Public Sub FillDataSet(ByVal dataSet As MyDataFormWizardSamp.MyDS)
        ' Turn off constraint checking before the dataset is filled.
        ' This allows the adapters to fill the dataset without concern
        ' for dependencies between the tables.
        dataSet.EnforceConstraints = False

        Try
            ' Open the connection.
            Me.oleDbConnection1.Open()
            ' Attempt to fill the dataset through the OleDbDataAdapter1.
            Me.oleDbDataAdapter1.Fill(dataSet)
            Me.oleDbDataAdapter2.Fill(dataSet)
        Catch fillException As System.Exception

            ' Add your error handling code here.


            Throw fillException
        Finally

            ' Turn constraint checking back on.


            dataSet.EnforceConstraints = True
            ' Close the connection whether or not the exception was thrown.
            Me.oleDbConnection1.Close()
        End Try
    End Sub

The UpdateDataSource method Updates the data source from the DataSet. The UpdateDataSet method calls
UpdateDataSource, which utilizes the Update method of the data adapters. Listing 4-9 shows the
UpdateDataSource method.

Listing 4-9. The UpdateDataSource and UpdataDataSet methods generated by the Data Form Wizard

    Public Sub UpdateDataSource(ByVal ChangedRows As MyDataFormWizardSamp.MyDS)
        Try
            ' The data source only needs to be updated if there are changes pending.
            If (ChangedRows IsNot Nothing) Then
                ' Open the connection.
                Me.oleDbConnection1.Open()
                ' Attempt to update the data source.
                oleDbDataAdapter1.Update(ChangedRows)
                oleDbDataAdapter2.Update(ChangedRows)
            End If
        Catch updateException As System.Exception

            ' Add your error handling code here.


            Throw updateException
        Finally

            ' Close the connection whether or not the exception was thrown.
            Me.oleDbConnection1.Close()
        End Try
    End Sub
What is Validation?
Validating user input can be quite a pain, especially if you do not know what
techniques and what namespaces are at your disposal. Because everyone has a
different way of doing things, my methods might not be 100% the same as your
methods. This is why I decided to make use of Regular Expressions here within
this article. Today you will learn how to use regular Expressions to validate user
input.

In simple terms, validation refers to ensuring entered data is well, valid.


Determining whether or not data is valid can sometimes be a painstaking
process as there are numerous tests that need to be thought of. These tests
include:

1. Format test – This test determines if the entered string is in the


correct format.
2. Type test – This test checks if the input is the correct type. For
example: Integers of dates that do not need conversion afterwards.
3. Permitted Character test – This test ensure that no illegal characters
are entered. For example: If a user is supposed to enter a name,
numbers and some special symbols must not be allowed.
4. Range test – This tests checks to see if entered values are within a
specified range. For example : If you are only supposed to type in 50
characters, you must not be able to enter more than fifty.
There are some more tests

Now, how do I perform these tests?

Well, sometimes a good structured and thought out If statement can suffice, but
it can become quite long and cumbersome in the future. Also, the more tests
you are performing, the slower your app might become. So what can we do? The
answer is simple: Use Regular Expressions! That is what they were invented
for.

What are Regular Expressions?


Regular Expressions are extremely powerful. They make use of a pattern
matching system to match the input with a certain pattern of data. This means
that as a programmer, you have the power to supply the exact pattern for the
input you desire in any text input field. By using Regular Expressions this way,
you can reduce the chances of getting errors at erratic times.

For more information regarding Regular Expressions, you are welcome to look at
these two MSDN articles:

 .NET Framework Regular Expressions


 Regular Expression Language – Quick Reference.

An Example Project
Because it is always easy to learn by doing things practically, you will be creating
an app that makes use of Regular Expressions to determine valid input.

Start Visual Studio and create a Desktop VB.NET application and design the form
to resemble Figure 1.
Figure 1 – Our Design

Code
The Regular Expression’s functionalities exist in
the System.Text.RegularExpressions namespace, so let us add that first:

Imports System.Text.RegularExpressions ' Regular Expressions


Namespace
Add the following four variables inside the General Declarations section:

Private NameValid As Boolean 'Is Name Valid?

Private SurnameValid As Boolean 'Is Surname Valid?

Private PhoneValid As Boolean 'Is Phone Number Valid?

Private EmailValid As Boolean 'Is Email Valid?


These objects will determine if all our data is valid or not. Based on each of these
variables’ values, we will know if the data is correct or not.

Validating Names
A name doesn’t generally contain weird symbols, and definitely not numbers.
That may seem like Captain Obvious speaking, but you’ll be amazed at some of
the data that gets entered into a name field. Sometimes people are just trying to
be funny, or they are literally trying to break your program. You could say that a
program’s testers are supposed to do this; yes, they should – nobody else
should.

Add the following inside your name Textbox’s Leave event:

Private Sub txtName_Leave(sender As Object, e As


System.EventArgs) Handles txtName.Leave

'If Not A Matching Format Entered

If Not Regex.Match(txtName.Text, "^[a-z]*$",


RegexOptions.IgnoreCase).Success Then 'Only Letters

MessageBox.Show("Please Enter Alphabetic


Characters Only!") 'Inform User

txtName.Focus() 'Return Focus

txtName.Clear() 'Clear TextBox

NameValid = False 'Boolean = False

Else

NameValid = True 'Everything Fine

End If
End Sub
Easy one to start with. The Leave event fires when the control loses focus. This
can be from the mouse clicking inside another field, or a Tab key being pressed
to navigate to the next input control.  I then created an If statement to
determine how the input data was formatted and whether or not the data is only
alphabetic. If the data is indeed only alphabetic letters (no symbols, no numbers
or any other punctuation characters) the test succeeds and stores True inside
the NameValid variable. If not, if there is even just one unallowed character that
is not supposed to be there, the Match method will return False.

See how quick it is to use Regular Expressions? Instead of you having to loop
through each character to determine what that character is, you simply need
the correct Regular Expression pattern. If you are uncertain about the pattern I
supplied, have a look here.

Validating Surnames
Well, the same logic should obviously apply here. Just a note, some surnames
contain spaces and even hyphens. My surname contains a space and it can get
quite frustrating if I am not allowed to enter my correct surname, or that I have
to edit my surname not to include a space. So, what I am trying to say is: make
sure you understand other cultures, or be aware of people with uncommon
names. Add this to validate the surname textbox:

Private Sub txtSurname_Leave(sender As Object, e As


System.EventArgs) Handles txtSurname.Leave

'Create A Pattern For Surname

Dim strSurname As String = "^[a-zA-Z\s]+$"

Dim reSurname As New Regex(strSurname) 'Attach Pattern


To Surname Textbox

'Not A Match
If Not reSurname.IsMatch(txtSurname.Text) Then

MessageBox.Show("Please Enter Alphabetic


Characters Only!")

txtName.Focus()

txtName.Clear()

SurnameValid = False

Else

SurnameValid = True

End If

End Sub
It is basically the exact same code for the Name box, but I just included the
capability to comprehend a space character as well.

Validating Phone Numbers


Now it gets trickier! Phone numbers usually follow some sort of format. This is
because it becomes more legible than just a normal set of numbers. People
expect to enter a phone number in a format similar to this: ###-###-####.
Sometimes there are even brackets surrounding the code. In certain cases the
international dialling code will also need to be supplied. Using Regular
expressions here, is basically the standard, even though it is a bit messy. Add
the following code to validate your phone number textbox:

'Function To Check Phone Number Validity

Public Function ValidatePhone(ByVal strPhoneNum As String)


As Boolean

''Create Reg Exp Pattern

Dim strPhonePattern As String = "^[1-9]\d{2}-[1-9]\


d{2}-\d{4}$"

'Create Reg Ex Object

Dim rePhone As New Regex(strPhonePattern)

'Something Typed In

If Not String.IsNullOrEmpty(strPhoneNum) Then

PhoneValid = rePhone.IsMatch(strPhoneNum) 'Check


Validity

Else

PhoneValid = False 'Not Valid / Empty

End If
Return PhoneValid 'Return True / False

End Function

Private Sub txtTel_LostFocus(sender As Object, e As


System.EventArgs) Handles txtTel.LostFocus

If Not ValidatePhone(txtTel.Text) Then 'Call Phone


Validation Function

MessageBox.Show("Please Enter Phone Number In


Correct Format!")

txtTel.Clear() 'Clear Input

txtTel.Focus() 'Return Focus

End If

End Sub
Here, I created a separate function to do all the work. This function is later called
inside the textbox’s LostFocus event, which also fires when a control loses the
focus. I set up my Expression to allow only numbers, but in the format I
explained earlier. If it isn’t valid input, it will clear the textbox and give it the
focus again; if it is valid, the PhoneValid variable gets updated to true.

Validating Emails
This one will be tough, be warned. Emails also follow a certain format. It is always
username at sub domain dot domain. Keep in mind that each country has its
own domain name, which sometimes will look like: .au  or  .za or .co.za. The point I
am trying to make is that there may be more than one dot after the at sign. Add
this code to validate the Email textbox:

Private Sub ValidateEmail()

'Set Up Reg Exp Pattern To Allow Most Characters, And


No Special Characters

Dim reEmail As Regex = New Regex("([a-zA-Z0-9_\-\.]


+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\." + _

")|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})",
_

RegexOptions.IgnoreCase _

Or RegexOptions.CultureInvariant _

Or RegexOptions.IgnorePatternWhitespace _

Or RegexOptions.Compiled _

Dim blnPossibleMatch As Boolean =


reEmail.IsMatch(txtEmail.Text)

If blnPossibleMatch Then

'Check If Entered Email Is In Correct Format

If Not
txtEmail.Text.Equals(reEmail.Match(txtEmail.Text).ToString)
Then
MessageBox.Show("Invalid Email Address!")

Else

EmailValid = True 'Email is Perfect

End If

Else 'Not A Match To Pattern

EmailValid = False 'Set Boolean Variable To False

MessageBox.Show("Invalid Email Address!") 'Inform


User

txtEmail.Clear() 'Clear Textbox

txtEmail.Focus() 'Set Focus To TextBox

End If

End Sub
Private Sub txtEmail_LostFocus(sender As Object, e As
System.EventArgs) Handles txtEmail.LostFocus

ValidateEmail() 'Check Email Validity

End Sub
The expression may look horrible to the layman’s eye, but look closer. It just
summarizes the above paragraph. Each email must have an @ sign. Each email
must have at least one . (dot) afterwards. Again, certain special characters are
obviously not allowed. This sub checks the email’s format and if it thinks that it
matches, it returns True and vice versa. Obviously this only works for the
formatting of the email. To check if the user has entered an email that actually
exists, you will have to find a different way such as to send a Registration
confirmation of some sorts.

You might also like