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(); } } }
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.