How to - Connect C# with SQL Server
In this section we will cover the basics of - How to - Connect C# with SQL Server
Below steps should be followed to connect Sql-Server(Database IDE) with C#(Windows Application Programming IDE)-
1- Open Sql Server Management Studio (SSMO).
2- Login in to SSMO by using Windows authentication OR SQL Server authentication-
![]() |
Windows authentication (It will use windows default credentials to login in SSMO) |
![]() |
SQL Server authentication (It will use SQL Server Administrator credentials to login in SSMO) |
3- Once you successfully log in SSMO, create a New Database in SSMO by
![]() |
Right clicking on Databases menu on Object Explorer of SSMO |
![]() |
You can also create database by using query from (New Query)
|
4- Once database is created, we will create table(s) in the database.
5- To create table, navigate to your database (in our case TestDB) in Object Explorer.
6- Double click on your database name, right click on Tables and then click on New Table from context menu.
7- You can create table by using table designer or also by query (here we are using table designer)
8- After creating table open Visual Studio (here we are using Visual Studio 2015).
9- In Visual Studio, click New project.
10- In New Project Window, click Templates (left side), inside templates, click Visual C#, then click on Windows.
11- In right pane, click on Windows Form Application.
12- In the name box, type Name and Location for your Project and click on OK.
13- Once the project is loaded, you will see default form (From1) in IDE.
14 - Click on Toolbox [(left side), if toolbox is not visible press Ctrl + W,X or you can go to View menu and click on Toolbox], and drag Button on the Form1 from toolbox.
15- Once you place the button on the From1, just double click on that button to write the code for CONNECTION (How to - Connect C# with SQL Server).
// Create a new object of SqlConnection Class SqlConnection Con = new SqlConnection(); // Assign ConnectionString to SqlConnection object Con.ConnectionString = "Data Source = YOUR-SERVER-NAME; Initial Catalog = YOUR-DATABASE; User ID = YOUR-USERNAME; Password = YOUR-PASSWORD;"; // After assiging ConnectionString to SqlConnection object Open the connection Con.Open(); // To check the state of connection (open or closed) prompt it in message box MessageBox.Show("Connection state is : " + Con.State.ToString());
18- Once you finish writing code and making necessary changes just press F5 button from keyboard or click on Start button(Visual Studio).
19- Once you press F5 or hit click Start your application will get executed, and you will get result as below
20- When you click the button a message will be displayed saying 'Connection state is : Open'. Congrats! You have successfully connected C# with SQL-Server now you can do further database operation with this connection.
Post a Comment