How to make global connection in C# .net?

Global Connection string will use in all Window form. You don't need to create Connection's in every form again and again. Just you need to pass the connection string object name. Just follow the below rules.

Step 1.

Create a New Window Application Form in Microsoft Visual Studio.

create new

Step 2.

After creating a new Application you will see default Window Form. Now just move to Solution Explorer Window and open App.config file by double clicking on it. Solution Explorer will locate right side corner of the Visual Studio. If you unable to see the Solution Explorer Window, simply press Ctrl + Alt + L or Click on View menu and choose Solution Explorer.

connection string

Step 3.

Add some XML code in App.config file. Just copy the below codes and paste it in your App.config file. Replace the information by your information.

Like you will change the data source = your data source name; data source is your SQL Server name.

connection string
	
  <connectionStrings>
  <add name="constr" connectionString="Data Source=NATURE-VAIO; database=raza; uid=sa;pwd=123456" providerName="System.Data.SqlClient" />
  </connectionStrings>
	

Step 4.

Now right click on your Application in Solution Explorer as shown in the below image.

Just move to your application → Add → Reference.

connection string

When you click on Reference option a new Window will open. Select framework option and then scroll down, find configuration namespace. Tick the both namespace.

connection string

Now move to your Window Form design view and double click on form. Add the below namespace in your code view form.

	
	 using System.Data.SqlClient;
     using System.Configuration;
        

In coding view of the form (Form1.cs) call the Connection String object of App.config file and pass it in the SqlConnection class.

	
	using System.Text;
        using System.Threading.Tasks;
        using System.Windows.Forms;
        using System.Data.SqlClient;
        using System.Configuration;

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

                SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString);
                
                private void Form1_Load(object sender, EventArgs e)
                {
            
                }
            }
        }
        

Now Your process has been Completed.

Watch Tutorial Video on YouTube

Watch and Subscribe Now

Post Your Comment