How to Create a Connection Between C# and SQL Server
Submitted by janobe on Wednesday, June 22, 2016 - 10:26.
In this tutorial, I will teach you how to create a connection between C#.net and SQL Server 2005 Express Edition. In this method, you can access the database that you have created in the SQL Server 2005 Express Edition wherein, you can select the tables and retrieve the data of it.
In here, we will use Microsoft Visual Basic Studio 2008 for creating this project.
After that, a “New Project” window will appear. Then, select “Visual C#” and create a new Windows Form Application and hit ok.
After creating a new Windows Form Application, do the Form just like this.
Double click the "Connect Me" button and do the following codes to establish the connection between SQL Server 2005 and C#.Net.
Here is another example that you can also perform.
For all students who need programmer for your thesis system or anyone who needs a sourcecode in any programming languages. You can contact me @ :
Email – [email protected]
Mobile No. – 09305235027 – tnt
Let's get started:
Create a databaase and name it "dbtest". Now, open Microsoft Visual Studio 2008 and create a new project.


Note: Put using System.Data.SqlClient; above the namespace to access sql server library and to avoid any errors.
- private void button1_Click(object sender, EventArgs e)
- {
- //initialize sql connection
- //set a connection string
- con.ConnectionString = "Data Source=.\\SQLEXPRESS;Database=dbtest;trusted_connection=true;";
- //opening connection
- con.Open();
- //validating connection
- if (con.State == ConnectionState.Open)
- {
- if (button1.Text == "Connect Me")
- {
- button1.Text = "Disconnect Me";
- label2.Text = "Connected";
- }
- else
- {
- button1.Text = "Connect Me";
- label2.Text = "Disconnected";
- con.Close();
- }
- }
- }
Output :

- private void button1_Click(object sender, EventArgs e)
- {
- //initialize sql connection
- //set a connection string
- con.ConnectionString = "Server=.\\SQLEXPRESS;" +
- "User Instance=true;" +
- "Integrated Security=true;" +
- "AttachDbFilename=" + Application.StartupPath + "\\dbtest.mdf;";
- //opening connection
- con.Open();
- //validating connection
- if (con.State == ConnectionState.Open)
- {
- if (button1.Text == "Connect Me")
- {
- button1.Text = "Disconnect Me";
- label2.Text = "Connected";
- }
- else
- {
- button1.Text = "Connect Me";
- label2.Text = "Disconnected";
- con.Close();
- }
- }
- }
Reminder:To make the second option work, you are required to put the database file(dbtest.mdf) inside the bin folder of your project.
Output :

Add new comment
- 201 views