C# Database Connection Tutorial With Example
C# Database Connection Tutorial With Example
C# Database Connection Tutorial With Example
(https://www.guru99.com/)
gurock.com Visit Site It also can work with new forms of databases
such as MongoDB (/mongodb-tutorials.html)and
MySQL.
https://www.guru99.com/c-sharp-access-database.html 1/37
In our
8/11/2018 examples, we will look at workingC#the Microsoft
Database SQL
Connection Server
Tutorial as our database. For
with Example
learning purposes, one can download and use the Microsoft SQL Server Express Edition,
which is a free database software provided by Microsoft.
In working with databases, the following are the concepts which are common to all databases.
1. Connection – To work with the data in a database, the first obvious step is the connection.
The connection to a database normally consists of the below-mentioned parameters.
1. Database name or Data Source – The first important parameter is the database
name to which the connection needs to be established. Each connection can only
work with one database at a time.
2. Credentials – The next important aspect is the username and password which
needs to be used to establish a connection to the database. It ensures that the
username and password have the necessary privileges to connect to the database.
3. Optional parameters - For each database type, you can specify optional
parameters to provide more information on how .net should handle the connection to
the database. For example, one can specify a parameter for how long the
connection should stay active. If no operation is performed for a specific period of
time, then the parameter would determine if the connection has to be closed.
2. Selecting data from the database – Once the connection has been established, the next
important aspect is to fetch the data from the database. C# can execute 'SQL' select
command against the database. The 'SQL' statement can be used to fetch data from a
specific table in the database.
3. Inserting data into the database – C# can also be used to insert records into the database.
Values can be specified in C# for each row that needs to be inserted into the database.
4. Updating data into the database – C# can also be used to update existing records into the
database. New values can be specified in C# for each row that needs to be updated into the
database.
5. Deleting data from a database – C# can also be used to delete records into the database.
Select commands to specify which rows need to be deleted can be specified in C#.
Ok, now that we have seen the theory of each operation, let's jump into the further sections to
look at how we can perform database operations in C#.
Username – sa
Password – demo123
https://www.guru99.com/c-sharp-access-database.html 2/37
We will
8/11/2018 see a simple Windows forms application to workTutorial
C# Database Connection withwith
databases.
Example We will have a simple
button called "Connect" which will be used to connect to the database.
Step 1) The first step involves the creation of a new project in Visual Studio. After launching
Visual Studio, you need to choose the menu option New->Project.
(/images/c-sharp-net/052716_0506_CAccessData1.png)
Step 2) The next step is to choose the project type as a Windows Forms application. Here, we
also need to mention the name and location of our project.
https://www.guru99.com/c-sharp-access-database.html 3/37
8/11/2018 C# Database Connection Tutorial with Example
(/images/c-sharp-net/052716_0506_CAccessData2.png)
1. In the project dialog box, we can see various options for creating different types of projects
in Visual Studio. Click the Windows option on the left-hand side.
2. When we click the Windows options in the previous step, we will be able to see an option for
Windows Forms Application. Click this option.
3. We then give a name for the application which in our case is "DemoApplication". We also
need to provide a location to store our application.
4. Finally, we click the 'OK' button to let Visual Studio to create our project.
Step 3) Now add a button from the toolbox to the Windows form. Put the text property of the
Button as Connect. This is how it will look like
https://www.guru99.com/c-sharp-access-database.html 4/37
8/11/2018 C# Database Connection Tutorial with Example
(/images/c-sharp-
net/052716_0506_CAccessData3.png)
Step 4) Now double click the form so that an event handler is added to the code for the button
click event. In the event handler, add the below code.
(/images/c-sharp-net/052716_0506_CAccessData4.png)
https://www.guru99.com/c-sharp-access-database.html 5/37
8/11/2018 C# Database Connection Tutorial with Example
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace DemoApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Code Explanation:-
1. The first step is to create variables, which will be used to create the connection string and
the connection to the SQL Server database.
2. The next step is to create the connection string. The connecting string needs to be specified
correctly for C# to understand the connection string. The connection string consists of the
following parts
https://www.guru99.com/c-sharp-access-database.html 6/37
8/11/2018 1. Data Source – This is the name of the
C# Database server
Connection on with
Tutorial which the database resides. In our
Example
When the above code is set, and the project is executed using Visual Studio, you will get the
below output. Once the form is displayed, click the Connect button.
Output:-
(/images/c-sharp-net/052716_0506_CAccessData5.png)
When you click on "connect" button, from the output, you can see that the database connection
was established. Hence, the message box was displayed.
1. A table called demotb. This table will be used to store the ID and names of various Tutorials.
2. The table will have 2 columns, one called "TutorialID" and the other called "TutorialName."
3. For the moment, the table will have 2 rows as shown below.
https://www.guru99.com/c-sharp-access-database.html 7/37
8/11/2018 C# Database Connection Tutorial with Example
TutorialID TutorialName
1 C#
2 ASP.Net
Let's change the code in our form, so that we can query for this data and display the information
via a Messagebox. Note that all the code entered below is a continuation of the code written for
the data connection in the previous section.
Step 1) Let's split the code into 2 parts so that it will be easy to understand for the user.
The first will be to construct our "select" statement, which will be used to read the data from
the database.
We will then execute the "select" statement against the database and fetch all the table rows
accordingly.
(/images/c-sharp-net/052716_0506_CAccessData6.png)
Code Explanation:-
The next is the "Output" which will contain all the table values.
2. The next step is to define the SQL statement, which will be used against our database. In
our case, it is "Select TutorialID, TutorialName from demotb". This will fetch all the rows from
the table demotb.
3. Next, we create the command object which is used to execute the SQL statement against
the database. In the SQL command, you have to pass the connection object and the SQL
string.
4. Next, we will execute the data reader command, which will fetch all the rows from the
demotb table.
5. Now that we have all the rows of the table with us, we need a mechanism to access the row
one by one. For this, we will use the while statement. The while statement will be used to
access the rows from the data reader one at a time. We then use the GetValue method to
get the value of TutorialID and TutorialName.
Step 2) In the final step, we will just display the output to the user and close all the objects
related to the database operation.
(/images/c-sharp-net/052716_0506_CAccessData7.png)
Code Explanation:-
1. We will continue our code by displaying the value of the Output variable using the
MessageBox. The Output variable will contain all the values from the demotb table.
2. We finally close all the objects related to our database operation. Remember this is always a
good practice.
When the above code is set, and the project is run using Visual Studio, you will get the below
output. Once the form is displayed, click the Connect button.
https://www.guru99.com/c-sharp-access-database.html 9/37
Output:-
8/11/2018 C# Database Connection Tutorial with Example
(/images/c-sharp-
net/052716_0506_CAccessData8.png)
From the output, you can clearly see that the program was able to get the values from the
database. The data is then displayed in the message box.
TutorialID TutorialName
1 C#
2 ASP.Net
Let's change the code in our form, so that we can insert the following row into the table
TutorialID TutorialName
3 VB.Net
https://www.guru99.com/c-sharp-access-database.html 10/37
So let's
8/11/2018 add the following code to our program.
C# Database The below
Connection code
Tutorial snippet will be used to insert an
with Example
(/images/c-sharp-net/052716_0506_CAccessData9.png)
Code Explanation:-
When the above code is set, and the project is executed using Visual Studio, you will get the
below output. Once the form is displayed, click the Connect button.
https://www.guru99.com/c-sharp-access-database.html 11/37
8/11/2018 C# Database Connection Tutorial with Example
Output:-
(/images/c-sharp-net/052716_0506_CAccessData10.png)
If you go to SQL Server Express and see the rows in the demotb table, you will see the row
inserted as shown below
(/images/c-sharp-
net/052716_0506_CAccessData11.png)
C# Update Database
Just like Accessing data, C# has the ability to update existing records from the database as
well. To showcase how to update records into our database, let's take the same table structure
which was used above.
TutorialID TutorialName
https://www.guru99.com/c-sharp-access-database.html 12/37
8/11/2018 C# Database Connection Tutorial with Example
1 C#
2 ASP.Net
3 VB.Net
Let's change the code in our form, so that we can update the following row. The old row value is
TutorialID as "3" and Tutorial Name as "VB.Net". Which we will update it to "VB.Net complete"
while the row value for Tutorial ID will remain same.
Old row
TutorialID TutorialName
3 VB.Net
New row
TutorialID TutorialName
3 VB.Net complete
So let's add the following code to our program. The below code snippet will be used to update
an existing record in our database.
(/images/c-sharp-net/052716_0506_CAccessData12.png)
https://www.guru99.com/c-sharp-access-database.html 13/37
Code
8/11/2018 Explanation:- C# Database Connection Tutorial with Example
When the above code is set, and the project is executed using Visual Studio, you will get the
below output. Once the form is displayed, click the Connect button.
Output:-
(/images/c-sharp-net/052716_0506_CAccessData13.png)
If you actually go to SQL Server Express and see the rows in the demotb table, you will see the
row was successfully updated as shown below.
https://www.guru99.com/c-sharp-access-database.html 14/37
8/11/2018 C# Database Connection Tutorial with Example
(/images/c-sharp-
net/052716_0506_CAccessData14.png)
Dele ng Records
Just like Accessing data, C# has the ability to delete existing records from the database as well.
To showcase how to delete records into our database, let's take the same table structure which
was used above.
TutorialID TutorialName
1 C#
2 ASP.Net
3 VB.Net complete
Let's change the code in our form, so that we can delete the following row
TutorialID TutorialName
3 VB.Net complete
So let's add the following code to our program. The below code snippet will be used to delete
an existing record in our database.
https://www.guru99.com/c-sharp-access-database.html 15/37
8/11/2018 C# Database Connection Tutorial with Example
(/images/c-sharp-net/052716_0506_CAccessData15.png)
Code Explanation:-
1. The Key difference in this code is that we are now issuing the delete SQL statement. The
delete statement is used to delete the row in the demotb table in which the TutorialID has a
value of 3.
2. In our data adapter command, we now associate the insert SQL command to our adapter.
We also then issue the ExecuteNonQuery method which is used to execute the Delete
statement against our database.
When the above code is set, and the project is executed using Visual Studio, you will get the
below output. Once the form is displayed, click the Connect button.
Output:-
(/images/c-sharp-net/052716_0506_CAccessData16.png)
If you actually go to SQL Server Express and see the rows in the demotb table, you will see the
row was successfully deleted as shown below.
https://www.guru99.com/c-sharp-access-database.html 16/37
8/11/2018 C# Database Connection Tutorial with Example
(/images/c-sharp-
net/052716_0506_CAccessData17.png)
But obviously, users don't want to see data sent via message boxes and would want better
controls to display the data. Let's take the below data structure in a table
TutorialID TutorialName
1 C#
2 ASP.Net
3 VB.Net complete
From the above data structure, the user would ideally want to see the TutorialID and Tutorial
Name displayed in a textbox. Secondly, they might want to have some sort of button control
which could allow them to go to the next record or to the previous record in the table. This
would require a bit of extra coding from the developer's end.
The good news is that C# can reduce the additional coding effort by allowing binding of controls
to data. What this means is that C# can automatically populate the value of the textbox as per a
particular field of the table.
So, you can have 2 textboxes in a windows form. You can then link one text box to the
TutorialID field and another textbox to the TutorialName field. This linking is done in the Visual
Studio designer itself, and you don't need to write extra code for this.
https://www.guru99.com/c-sharp-access-database.html 17/37
Visual
8/11/2018 Studio will ensure that it writes the code for
C# Database you to
Connection ensure
Tutorial the linkage works. Then when
with Example
you run your application, the textbox controls will automatically connect to the database, fetch
the data and display it in the textbox controls. No coding is required from the developer's end to
achieve this.
In our example, we are going to create 2 textboxes on the windows form. They are going to
represent the Tutorial ID and Tutorial Name respectively. They will be bound to the Tutorial ID
and TutorialName fields of the database accordingly.
Step 1) Construct the basic form. In the form drag and drop 2 components- labels and
textboxes. Then carry out the following substeps
Below is the how the form would look like once the above-mentioned steps are performed.
(/images/c-sharp-
net/052716_0506_CAccessData18.png)
Step 2) The next step is to add a binding Navigator to the form. The binding Navigator control
can automatically navigate through each row of the table. To add the binding navigator, just go
to the toolbox and drag it to the form.
https://www.guru99.com/c-sharp-access-database.html 18/37
8/11/2018 C# Database Connection Tutorial with Example
(/images/c-sharp-net/052716_0506_CAccessData19.png)
Step 3) The next step is to add a binding to our database. This can be done by going to any of
the Textbox control and clicking on the DataBindings->Text property. The Binding Navigator is
used to establish a link from your application to a database.
When you perform this step, Visual Studio will automatically add the required code to the
application to make sure the application is linked to the database. Normally the database in
Visual Studio is referred to as a Project Data Source. So to ensure the connection is
established between the application and the database, the first step is to create a project data
source.
The following screen will show up. Click on the link- "Add Project Data Source". When you click
on the project data source, you will be presented with a wizard; this will allow you to define the
database connection.
https://www.guru99.com/c-sharp-access-database.html 19/37
8/11/2018 C# Database Connection Tutorial with Example
(/images/c-sharp-net/052716_0506_CAccessData20.png)
Step 4) Once you click on the Add Project Data Source link, you will be presented with a wizard
which will be used to create a connection to the demotb database. The following steps show in
detail what needs to be configured during each step of the wizard.
1. In the screen which pops up , choose the Data Source type as Database and then click on
next button.
https://www.guru99.com/c-sharp-access-database.html 20/37
8/11/2018 C# Database Connection Tutorial with Example
(/images/c-sharp-net/052716_0506_CAccessData21.png)
2. In the next screen, you need to start the creation of the connection string to the database.
The connection string is required for the application to establish a connection to the
database. It contains the parameters such as server name, database name, and the name
of the driver.
1. Click on the New connection button
2. Choose the Data Source as Microsoft SQL Server
3. Click the Continue button.
https://www.guru99.com/c-sharp-access-database.html 21/37
8/11/2018 C# Database Connection Tutorial with Example
(/images/c-sharp-net/052716_0506_CAccessData22.png)
https://www.guru99.com/c-sharp-access-database.html 22/37
8/11/2018 C# Database Connection Tutorial with Example
(/images/c-sharp-net/052716_0506_CAccessData23.png)
4. In this screen, we will confirm all the settings which were carried on the previous screens.
1. Choose the option "Yes" to include sensitive data in the connection string
2. Click on the "Next" button.
https://www.guru99.com/c-sharp-access-database.html 23/37
8/11/2018 C# Database Connection Tutorial with Example
(/images/c-sharp-net/052716_0506_CAccessData24.png)
5. In the next screen, click on the "Next" button to confirm the creation of the connection string
https://www.guru99.com/c-sharp-access-database.html 24/37
8/11/2018 C# Database Connection Tutorial with Example
(/images/c-sharp-net/052716_0506_CAccessData25.png)
6. In this step,
1. Choose the tables of Demotb, which will be shown in the next screen.
2. This table will now become an available data source in the C# project
https://www.guru99.com/c-sharp-access-database.html 25/37
8/11/2018 C# Database Connection Tutorial with Example
(/images/c-sharp-net/052716_0506_CAccessData26.png)
When you click the Finish button, Visual Studio will now ensure that the application can query
all the rows in the table Demotb.
Step 5) Now that the data source is defined, we now need to connect the TutorialID and
TutorialName textbox to the demotb table. When you click on the Text property of either the
TutorialID or TutorialName textbox, you will now see that the binding source to Demotb is
available.
For the first text box choose the Tutorial ID. Repeat this step for the second textbox and choose
the field as TutorialName. The below steps shows how we can navigate to each control and
change the binding accordingly.
https://www.guru99.com/c-sharp-access-database.html 26/37
8/11/2018 C# Database Connection Tutorial with Example
(/images/c-sharp-net/052716_0506_CAccessData27.png)
2. In the Properties window, you will see the properties of the TutorialID textbox. Go to the text
property and click on the down arrow button.
(/images/c-sharp-
net/052716_0506_CAccessData28.png)
3. When you click the down arrow button, you will see the demotbBinding Source option. And
under this, you will see the options of TutorialName and TutorialID. Choose the Tutorial ID
one.
https://www.guru99.com/c-sharp-access-database.html 27/37
8/11/2018 C# Database Connection Tutorial with Example
(/images/c-sharp-net/052716_0506_CAccessData29.png)
Repeat the above 3 steps for the Tutorial Name text box.
Step 6) Next we need to change the Binding Source property of the BindingNavigator to point
to our Demotb data source. The reason we do this is that the Binding Navigator also needs to
know which table it needs to refer to.
The Binding Navigator is used to select the next or previous record in the table. So even though
the data source is added to the project as a whole and to the text box control, we still need to
ensure the Binding Navigator also has a link to our data source. In order to do this, we need to
click the Binding navigator object, go to the Binding Source property and choose the one that is
available
https://www.guru99.com/c-sharp-access-database.html 28/37
8/11/2018 C# Database Connection Tutorial with Example
(/images/c-sharp-net/052716_0506_CAccessData30.png)
Next, we need to go to the Properties window so that we can make the change to Binding
Source property.
(/images/c-sharp-net/052716_0506_CAccessData31.png)
When all of the above steps are executed successfully, you will get the below-mentioned output.
Output:-
https://www.guru99.com/c-sharp-access-database.html 29/37
8/11/2018 C# Database Connection Tutorial with Example
(/images/c-sharp-
net/052716_0506_CAccessData32.png)
Now when the project is launched, you can see that the textboxes automatically get the values
from the table.
(/images/c-sharp-
net/052716_0506_CAccessData33.png)
When you click the Next button on the Navigator, it automatically goes to the next record in the
table. And the values of the next record automatically come in the text boxes
C# DataGridView
Data Grids are used to display data from a table in a grid-like format. When a user sees's table
data, they normally prefer seeing all the table rows in one shot. This can be achieved if we can
display the data in a grid on the form.
C# and Visual Studio have inbuilt data grids, this can be used to display data. Let's take a look
at an example of this. In our example, we will have a data grid, which will be used to display the
Tutorial ID and Tutorial Name values from the demotb table.
https://www.guru99.com/c-sharp-access-database.html 30/37
Step1) Drag the DataGridView controlC#
8/11/2018 from theConnection
Database toolboxTutorial
to thewithForm
Examplein Visual Studio. The
DataGridView control is used in Visual Studio to display the rows of a table in a grid-like format.
(/images/c-sharp-net/052716_0506_CAccessData34.png)
Step 2) In the next step, we need to connect our data grid to the database. In the last section,
we had created a project data source. Let's use the same data source in our example.
1. First, you need to choose the grid and click on the arrow in the grid. This will bring up the
grid configuration options.
2. In the configuration options, just choose the data source as demotbBindingSource which
was the data source created in the earlier section.
https://www.guru99.com/c-sharp-access-database.html 31/37
8/11/2018 C# Database Connection Tutorial with Example
(/images/c-sharp-net/052716_0506_CAccessData35.png)
If all the above steps are executed as shown, you will get the below-mentioned output.
Output:-
(/images/c-sharp-
net/052716_0506_CAccessData36.png)
From the output, you can see that the grid was populated by the values from the database.
Summary
https://www.guru99.com/c-sharp-access-database.html 32/37