orange database cylinder, hand-drawn storage icon, database label, white background

Create Database in Microsoft Visual Studio

2.5K Views
40
700
60
25
60
PCBWay

Hello friends! Today we will create a contact database in Microsoft Visual Studio and connect it to a Visual Basic Windows Forms application. We will begin with an empty project, create a table, enter sample contacts and display those contacts in both a grid and a details form.

This tutorial retains the original Visual Studio 2010 walkthrough and screenshots. Its main purpose is to explain the database, dataset and data-binding workflow used by that application. If you are maintaining an older VB project or learning how its generated components work, the same distinctions will help you understand where records are loaded, edited and saved.

After completing this part, continue with button controls in a VB database application and updating a database table with VB programming. Our earlier Visual Basic serial-port tutorial covers a different application of Windows Forms.

orange database cylinder, hand-drawn storage icon, database label, white background
Figure: A database illustration introduces the Visual Basic contact-management tutorials.

What We Are Going to Build

Our application stores one contact per row. The grid displays several contacts at once, while the details controls display the currently selected contact. Both views should use the same binding source so that selecting a different row updates the details automatically.

contact records grid, selected record details, navigation toolbar, Visual Basic Windows Form
Figure: The original contact application displays a grid and details controls for the current record.

Before opening the designer, distinguish these parts:

PartRole in this project
SQL Server databaseStores the persistent contact records and enforces the table's constraints.
Contacts.mdfThe primary database file used by the sample SQL Server database.
ContactsDataSetA typed, in-memory representation of the application's tables and rows.
Contact_FormBindingSourceConnects the contact data to controls and tracks the current record.
TableAdapterLoads records and sends supported changes to the database.
DataGridView and text boxesPresent records and allow the user to edit them.

A dataset is not the database file. This distinction becomes important when a contact appears on the screen but disappears after the program closes.

Choose the Correct Project and Database Environment

The original example uses Visual Basic, Windows Forms and the .NET Framework. In Visual Studio 2010, the project template is called Windows Forms Application. In a newer installation, choose a Windows Forms App (.NET Framework) project when following this particular designer-based workflow.

Current Microsoft guidance treats typed datasets as a legacy .NET Framework approach and recommends considering Entity Framework Core for new applications. The database designer walkthrough also identifies the relevant desktop and data tooling. We will stay with the dataset approach here so the instructions remain connected to the original project.

Visual Studio is the development environment; SQL Server is the database engine. Creating an MDF file does not make the engine unnecessary. Older Visual Studio 2010 examples commonly use SQL Server Express, sometimes through its user-instance feature. LocalDB arrived with SQL Server 2012, so a connection string copied from a modern tutorial may not match an original 2010 installation. See Microsoft's LocalDB introduction for that version distinction.

Use a working SQL Server connection appropriate to your installation. Do not replace a valid server name with (localdb)\MSSQLLocalDB just because another example contains it. Start by confirming which engine your project actually uses.

Step 1: Create the Visual Basic Project

Open Visual Studio and choose New Project.

Visual Studio 2010 Start Page, New Project command, project navigation links, development workspace
Figure: Start a new Windows Forms project from the Visual Studio Start Page.

Select Visual Basic and the Windows Forms application template. Give the project a meaningful name, such as ContactManager, and choose a folder where you can keep the solution and its database files together during development.

New Project dialog, Visual Basic template group, Windows Forms Application choice, Contact Form project name
Figure: Choose the Visual Basic Windows Forms template for the contact application.

After creation, the form designer displays the empty main form. Save the project before adding the database so that generated files have a definite location.

blank contact form, Windows Forms designer, Toolbox panel, Properties window
Figure: The new form provides the layout surface for the database-bound controls.

At this point, we have a user-interface project, but no contact storage. The next step creates the database that the form will eventually use.

Step 2: Add the Database File

  1. Open Solution Explorer from the View menu if it is hidden.
  2. Right-click the project, choose Add and then New Item.
  3. Find the database item template supported by your installed tools.
Solution Explorer project menu, Add submenu, New Item command, contact form designer
Figure: Use the project's Add New Item command to add the database file.

In the original environment, select Service-based Database, name the file Contacts.mdf and add it to the project.

Service-based Database template, Contacts.mdf filename, Add New Item dialog, Add button
Figure: The original project creates Contacts.mdf from the Service-based Database template.

If the Data Source Configuration Wizard opens immediately, cancel it for now. We will create the table before choosing which database objects the dataset should contain.

Data Source Configuration Wizard, database model choices, highlighted Cancel button, Contacts database project
Figure: Cancel the initial wizard until the contact table has been created.

The database is now present, but it has no contact table. An MDF file is also not an ordinary document that you should move or copy while its database engine is using it. For this exercise, let Visual Studio and SQL Server manage the connection through their normal tools.

Step 3: Create the Contact Table

Open the database connection in Server Explorer, expand the database and locate Tables. Right-click that node and choose Add New Table.

Contacts database connection, Tables node, Add New Table command, Server Explorer panel
Figure: Open the table designer from the database's Tables node.

Create the primary key

Name the first column ContactID, choose int and disallow nulls. Set this column as the primary key. In its Identity Specification properties, enable identity generation with a seed of 1 and increment of 1.

The original text mixed the names ColumnID and ContactID. Use ContactID consistently in your table and any code that refers to it.

ContactID integer column, primary key command, Identity Specification properties, automatic identity setting
Figure: The original designer configures ContactID as an automatically generated primary key.

The primary key identifies a row; the identity property supplies values for that key. They perform different jobs. An identity value is not the number of contacts currently stored. If IDs 1, 2 and 3 exist and you delete contact 2, two contacts remain even though the largest ID is 3. Failed inserts and other events can also leave gaps. Microsoft documents these limits in the SQL Server IDENTITY reference.

Add suitable contact fields

The original screenshots use short text fields. For a fresh practice database, the following schema gives us a clear example with Unicode names and optional contact details. If you already built the original project, keep your existing field names or update the bindings to match any deliberate schema changes.

ColumnSQL typeAllow nulls?Purpose
ContactIDint IDENTITY(1,1)NoPrimary key generated by SQL Server.
FullNamenvarchar(100)NoThe contact's display name.
Phonenvarchar(30)YesPhone text, including prefixes and formatting.
Emailnvarchar(254)YesAn optional email address.
Addressnvarchar(250)YesAn optional postal address.

A telephone number belongs in a text field because you do not calculate with it and must preserve characters such as a leading plus sign or zero. A person's name should not be a primary key because different people can have identical names.

Save the table as Contact Form to remain consistent with this tutorial series. SQL identifiers containing a space need delimiters in statements, such as dbo.[Contact Form]. Visual Studio commonly converts the space to an underscore in generated component names.

contact field definitions, table name dialog, Contact Form table name, database table designer
Figure: Save the contact table after defining the original project's fields.

Equivalent SQL definition

If you prefer entering the schema in a query window, the following creates the same example table in your selected practice database. Use either this script or the table designer; do not run it again after the table already exists.

CREATE TABLE dbo.[Contact Form]
(
    ContactID int IDENTITY(1,1) NOT NULL,
    FullName nvarchar(100) NOT NULL,
    Phone nvarchar(30) NULL,
    Email nvarchar(254) NULL,
    Address nvarchar(250) NULL,
    CONSTRAINT PK_ContactForm PRIMARY KEY (ContactID),
    CONSTRAINT CK_ContactForm_FullName
        CHECK (LEN(LTRIM(RTRIM(FullName))) > 0)
);

The check constraint rejects empty or ordinary space-only names. Application validation should give the user a friendly message before such a value reaches the database. SQL constraints provide another layer of enforcement; they do not design the form's error messages for you.

Step 4: Enter a Few Sample Contacts

Expand Tables, right-click Contact Form and choose Show Table Data. Some newer tools call this command View Data.

Contact Form table node, Show Table Data command, Server Explorer menu, database connection tree
Figure: Open the table's data editor to enter sample contacts.

Enter two or three fictional contacts. Leave ContactID to the database engine. Fill the required name and any optional details you want to display, then complete the row edit so the data editor can submit it.

contact data rows, table data editor, Save Project dialog, Contact Form project name
Figure: Original sample records are visible behind the project-save dialog; saving a project is separate from committing a data row.

Saving a table's design and committing a data row are different operations. A schema-save dialog names or changes a table; it does not replace the data editor's row submission behavior. If an error icon appears, inspect its message before assuming the contact has been stored.

A simple read-only query can show the records in a predictable order:

SELECT ContactID, FullName, Phone, Email, Address
FROM dbo.[Contact Form]
ORDER BY ContactID;

To count records, use SELECT COUNT(*) FROM dbo.[Contact Form];. Do not calculate the count from the highest identity value.

Step 5: Create the Application's Data Source

Now that our table exists, open the Data menu and choose Add New Data Source in the original Visual Studio 2010 interface.

Visual Studio Data menu, Add New Data Source command, contact form designer, database project workspace
Figure: Start the wizard after the database table is ready.

Choose Database as the source type.

Data Source Configuration Wizard, Database source choice, source type icons, Next button
Figure: Select Database as the source for the contact application's data model.

Choose the dataset model when prompted. This is the object model that the Windows Forms designer will bind to the controls.

database model selection, Dataset option, Entity Data Model alternative, Next button
Figure: Use the dataset model for this original .NET Framework Windows Forms workflow.

Select the connection for Contacts.mdf. Inspect the server and file path so that you do not accidentally select another copy of a similarly named database.

data connection wizard page, Contacts database selection, connection string section, Next button
Figure: Choose the connection that points to the intended Contacts database.

Save the connection setting when prompted, expand Tables and select Contact Form. Name the dataset ContactsDataSet and finish the wizard.

database object selection, Contact Form table checkbox, selected contact fields, dataset name field
Figure: Select the contact table and finish generating the typed dataset.

Visual Studio generates the dataset schema and related components. The wizard does not move all your contact records into the application's source code; the application still needs to load records at runtime. Microsoft's Windows Forms data-source walkthrough documents the database and dataset selection process.

If the table is missing from the selection list, refresh the connection and confirm that the table was created in this database. If you add columns later, update the dataset schema and affected bindings; a database change does not automatically repair every generated control.

Step 6: Add Grid and Details Views

Open the form designer and the Data Sources window. Drag the Contact Form table onto the form with its display type set to a grid. Resize the resulting DataGridView so that the useful columns are visible.

Data Sources table node, contact DataGridView, generated navigation toolbar, Windows Forms designer
Figure: Dragging the table onto the form creates the grid and related binding components.

Next, use the table's drop-down menu in Data Sources and select Details.

Data Sources display menu, Details option, existing contact grid, Windows Forms designer
Figure: Change the table's display type to Details before adding individual field controls.

Drag the table onto another area of the form. This adds individual controls for the contact fields.

bound contact text boxes, existing DataGridView, Data Sources field list, Windows Forms designer
Figure: The details controls and grid should share the same contact binding source.

Check that the grid and details controls use the same Contact_FormBindingSource. Otherwise, each view can maintain a different current position. Keep the identity field read-only, since SQL Server assigns it. Set useful labels, a sensible tab order and text-box length limits that agree with the schema.

The form should now resemble the original combined view:

contact records grid, selected record details, navigation toolbar, Visual Basic Windows Form
Figure: The original contact application displays a grid and details controls for the current record.

The designer also adds nonvisual components below the form. They are part of the data-binding arrangement, not database records. Microsoft's Windows Forms binding documentation explains how dragging a data source creates these controls and components.

Understand Loading, Editing and Saving

Load records when the form opens

The designer often adds a Fill call to the form's Load event:

Me.Contact_FormTableAdapter.Fill(Me.ContactsDataSet.Contact_Form)

This uses the TableAdapter's configured query to populate the in-memory table. Generated names can differ, so inspect the component names in your project instead of adding another adapter just to match a sample line.

A TableAdapter's Fill and Update operations have different purposes. Fill reads data; Update sends tracked changes back through its configured commands. The TableAdapter documentation describes these operations. Repeatedly calling Fill is not a substitute for saving and may replace unsaved in-memory data depending on its settings.

Commit edits before sending changes

For a single-table form, the core save sequence can look like this inside the existing Save event handler:

Try
    If Not Me.ValidateChildren() Then
        Return
    End If

    Me.Contact_FormBindingSource.EndEdit()
    Dim affected As Integer =
        Me.Contact_FormTableAdapter.Update(
            Me.ContactsDataSet.Contact_Form)

    MessageBox.Show(
        affected.ToString() & " row changes saved.",
        "Contacts")
Catch ex As System.Data.DBConcurrencyException
    MessageBox.Show(
        "A record changed in the database. Review the conflict before retrying.",
        "Save conflict")
Catch ex As Exception
    MessageBox.Show(
        "The contacts could not be saved: " & ex.Message,
        "Save failed")
End Try

Validation checks only the rules you implement; it does not automatically know that a name is required. EndEdit() completes the current binding edit. The adapter's Update call then handles pending inserts, updates and deletes for its table. An empty Catch block would hide failures, so the sample reports them.

If your generated form uses a configured TableAdapterManager, its UpdateAll(Me.ContactsDataSet) call can coordinate updates instead. Use the project's chosen save path once; do not invoke both methods for the same operation. Microsoft's saving dataset changes guide explains the distinction between local edits and database updates.

Why Do Records Sometimes Disappear After Restarting?

First check whether the Save event ran successfully. Then inspect which database file the running application actually opened. A project can have one MDF file in its source folder and another in a build-output folder such as bin\Debug.

The database item's Copy to Output Directory setting affects this behavior:

SettingPractical effect to consider
Copy alwaysA build can overwrite the runtime copy with the project copy.
Copy if newerCopying depends on file timestamps; it is not a database backup strategy.
Do not copyThe application must still point to a database that exists at runtime.

Do not toggle these settings blindly. Compare the configured connection, the resolved file location and the database you inspect in Server Explorer. If your program saved into the runtime copy, opening the source copy will show different data even when the save worked.

Older connection strings may also contain User Instance=True. That belongs to the SQL Server Express user-instance workflow; it is not a general-purpose fix for every SQL Server connection problem.

Review the Finished Database Form

Use a small set of fictional contacts to check the behavior in your own environment. Add one contact, save it, reopen the program and confirm it remains. Edit a field and save again. Finally, remove that test contact, save the deletion and reopen the program.

Also try an invalid name and confirm that the application explains the problem. Selecting different grid rows should update the details controls. These exercises distinguish a form that only displays data from one that reliably persists edits.

We now have the foundation for the next lesson: a contact table, a typed dataset, a binding source and data-bound controls. Custom Add, Save, Remove and navigation buttons will use those existing components.

Frequently Asked Questions

Is Visual Studio itself a database?

No. It provides development and database-management tools. SQL Server stores and processes the data used by this example.

Why use an integer ID when contacts already have names?

Names can change and need not be unique. A separate key gives each contact a stable identifier without treating a person's name as a unique value.

Why does a new row appear before I press Save?

The form is showing its in-memory data. Adding a row there and committing it to SQL Server are separate steps.

Can I use a newer Visual Studio version?

Yes, with compatible .NET Framework and database tooling, but menus and database connections may differ. Match the project type and installed engine before following the screenshots.

Does copying the EXE copy the complete application?

Not necessarily. The receiving computer also needs the required runtime, database engine or server access, configuration and deployed database resources. The development folder is not a complete deployment plan.

What should I do when the Save button reports a conflict?

Preserve the user's pending values and investigate the row that changed. Do not silently reload everything or claim success, because doing so can discard edits or hide a failed update.


Comments

31

Join the conversation

Reply3

qasim.iqbal@gmail.com .... That's my id and I have joined the newsletter as well kindly send me this complete project.

Thanks in advance

Reply4

Philip Thanks bro, I have posted the second part of this tutorial. enjoy !!!

@ William Thanks for appreciation bro.

@ Qasim I have emailed to to you. Thanks for subscribing and stay connected.... :))

1 reply
Reply5

Hello my friend thanks for this tutorial
My name is PAUL I'm from Greece
I have one problem when i use the programm and i wrote in my language
shows the character with question marks .did you know what to do with this?

3 replies
Reply5.1
Replying to adiono

Hi,

Test it using words of English .... I think the problem is because the software is not supporting your language .... Test it with english or numeric words .... if its work fine then check for the the language update ....

Let me know if you cant resolve this issue.

Thanks.

1 reply
1 reply
Reply11

hi
I want to create a database using RFID parking system, database using Visual Basic, can help me to create a database entry and exit to the parking system?

1 reply
Reply19

That is best and helpful tutor! Am new to VB , Also want to learn how to create database using VB, Pls can u send Send me all tutorials you have on Visual basic especially on database. thanks sir. emmy

NB I WILL LIKE TO SUBSCRIBE FOR YOUR NEWS LETTER Thank u

1 reply
Reply19.1
Replying to adiono

Hi,

Thanks for the appreciation. it works as a fuel for our team. :))

All the links for dealing with database in vb are given in this article. I think I have posted 3 or 4 article and these will be enough for you to learn the basics of database handling.

Thanks.

Reply22

sir its easy to design tables can you make a tutorial how data will be saved ,delete , update,find ...i get sucess to make all you explain but data in tables are not storing properly .please provide a solution for this one.
thank you