Pages

Wednesday, August 22, 2018

How to connect C# to MS SQL Server Database

We will now create a simple Windows form application to work with a database. This form has button called "Connect" which will be use to connect a database.

STEP 01: Open Visual Studio on your computer.





STEP 02: Go to File > New > Project. The New Project window will show.



STEP 03: Select Windows Forms Application and enter a name and location for the application. Then, click OK button.



STEP 04: Add Button component on the center of the form.


STEP 05: Double click the Button of the form and copy and paste the code below.

using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace Connect_To_MSSQL_Database
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //Initialize connection
            //Data Source = your server
            //Initial Catalog = your database name
            //User = server username
            //Password = server password
            string connetionString = @"Data Source=localhost;Initial Catalog=Application;User ID=sa;Password=11231990";

            try
            {
                //Create new connection
                SqlConnection con = new SqlConnection(connetionString);

                //Check the connection is closed
                if (con.State == ConnectionState.Closed)
                {
                    //Open the connection
                    con.Open();

                    MessageBox.Show("Connection is now Open  !");
                }
                else
                {
                    MessageBox.Show("Connection is already Open  !");

                    //Close the connection
                    con.Close();
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show("Connection failed: " + ex.Message);
            }
            finally
            {
              //Even the connection is failed or succeeded, this block execute.
            }
       


        }
    }
}

STEP 06: Press F5 or click the Start button on toolbar to run the application. Then, click the button to connect the database. Finally, your now connected.



Download source code below:
https://drive.google.com/file/d/1MvOEFlzl6r5hyWKd0-FYRJxTiWpddqFY/view?usp=sharing