How to Make Global Connection String.

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
database = your database name;
uid = your sql server user name;
pwd = your sql server password;

connection string
	
	
  
  
	

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.

Advertisement here

Share this Page.