
Create Database in Microsoft Visual Studio

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.
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.
Before opening the designer, distinguish these parts:
| Part | Role in this project |
|---|---|
| SQL Server database | Stores the persistent contact records and enforces the table's constraints. |
Contacts.mdf | The primary database file used by the sample SQL Server database. |
ContactsDataSet | A typed, in-memory representation of the application's tables and rows. |
Contact_FormBindingSource | Connects the contact data to controls and tracks the current record. |
| TableAdapter | Loads records and sends supported changes to the database. |
| DataGridView and text boxes | Present 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.
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.
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.
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
- Open Solution Explorer from the View menu if it is hidden.
- Right-click the project, choose Add and then New Item.
- Find the database item template supported by your installed tools.
In the original environment, select Service-based Database, name the file Contacts.mdf and add it to the project.
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.
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.
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.
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.
| Column | SQL type | Allow nulls? | Purpose |
|---|---|---|---|
| ContactID | int IDENTITY(1,1) | No | Primary key generated by SQL Server. |
| FullName | nvarchar(100) | No | The contact's display name. |
| Phone | nvarchar(30) | Yes | Phone text, including prefixes and formatting. |
nvarchar(254) | Yes | An optional email address. | |
| Address | nvarchar(250) | Yes | An 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.
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.
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.
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.
Choose Database as the source type.
Choose the dataset model when prompted. This is the object model that the Windows Forms designer will bind to the controls.
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.
Save the connection setting when prompted, expand Tables and select Contact Form. Name the dataset ContactsDataSet and finish the wizard.
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.
Next, use the table's drop-down menu in Data Sources and select Details.
Drag the table onto another area of the form. This adds individual controls for the contact fields.
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:
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:
| Setting | Practical effect to consider |
|---|---|
| Copy always | A build can overwrite the runtime copy with the project copy. |
| Copy if newer | Copying depends on file timestamps; it is not a database backup strategy. |
| Do not copy | The 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.
awesome post man
waiting for the next one
kindly post it asap as i am working on a similar project in the lab
Thanks again
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
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
It is really nice explanation. Further this, I want to add database for any application layer. How can i do that?
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
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.
Thanks for your reply when i use english words is ok
i check for unicodes and i change the fields to greek_BIN in the data table but the problem is there, change the greek letters with ??????
hmmm that's just because of the non supportive behavior of software for this language .... I think you should go with English.
tanks.can i update this table with ma phn msg
1 reply
Yeah you can do that as well, not that difficult.
That is best and helpful tutor! so please send me the application with its .exe and full tutor.
thanks a lot
Hello
thanks for your explaning
i have problem .... i want to add another form for searching ? how can make full search ?
1 reply
Contact me on skype n I'll explain but adding a search form is quite simple, search a little online n you will find the solution
I love this tutorial, is very straight forward
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?
Its a great tutor, best tutor i hv ever read, keep it up
How to connect rfid data with database visual studio ultimate? What i must to do?
1 reply
Hi, Kindly add me to Skype and I will help you out. Its not that easy. Thanks.
Hi, your tutorial is indeed great. I wish to have your tutorials on Visual basic, particularly database. Thanks. .
Very nice sir
hats off
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
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.
thank you sir , for your quick reply, keep the fire burning . i will go through the guides and get back to u sir,
happy weekend .
Visual Studio 2013
I can't make Step 5 - I don't have a DATA in soft. How Attach a Data Source in VS2013 ?
Regards
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

























Comments
31