How to Create a Connection Between C# and SQL Server

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.

Let's get started:

Create a databaase and name it "dbtest". Now, open Microsoft Visual Studio 2008 and create a new project. fig1 After that, a “New Project” window will appear. Then, select “Visual C#” and create a new Windows Form Application and hit ok. fig2 After creating a new Windows Form Application, do the Form just like this. fig3 Double click the "Connect Me" button and do the following codes to establish the connection between SQL Server 2005 and C#.Net.
Note: Put using System.Data.SqlClient; above the namespace to access sql server library and to avoid any errors.
  1. private void button1_Click(object sender, EventArgs e)
  2. {
  3. //initialize sql connection
  4. SqlConnection con = new SqlConnection();
  5. //set a connection string
  6. con.ConnectionString = "Data Source=.\\SQLEXPRESS;Database=dbtest;trusted_connection=true;";
  7.  
  8. //opening connection
  9. con.Open();
  10. //validating connection
  11.  
  12. if (con.State == ConnectionState.Open)
  13. {
  14. if (button1.Text == "Connect Me")
  15. {
  16. button1.Text = "Disconnect Me";
  17. label2.Text = "Connected";
  18. }
  19. else
  20. {
  21. button1.Text = "Connect Me";
  22. label2.Text = "Disconnected";
  23. con.Close();
  24. }
  25.  
  26. }
  27.  
  28. }

Output :

Output Here is another example that you can also perform.
  1. private void button1_Click(object sender, EventArgs e)
  2. {
  3. //initialize sql connection
  4. SqlConnection con = new SqlConnection();
  5. //set a connection string
  6. con.ConnectionString = "Server=.\\SQLEXPRESS;" +
  7. "User Instance=true;" +
  8. "Integrated Security=true;" +
  9. "AttachDbFilename=" + Application.StartupPath + "\\dbtest.mdf;";
  10.  
  11.  
  12.  
  13.  
  14. //opening connection
  15. con.Open();
  16. //validating connection
  17.  
  18. if (con.State == ConnectionState.Open)
  19. {
  20. if (button1.Text == "Connect Me")
  21. {
  22. button1.Text = "Disconnect Me";
  23. label2.Text = "Connected";
  24. }
  25. else
  26. {
  27. button1.Text = "Connect Me";
  28. label2.Text = "Disconnected";
  29. con.Close();
  30. }
  31.  
  32. }
  33.  
  34. }
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 :

Output 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

Add new comment