Create Connection String and Use in Multiple Form in C#

Introduction

In this article I will explain how to create a connection string once and then use the connection in multiple forms in Windows applications. In web applications we create a connection string in the web.config file and use this connection in multiple pages but in Windows Forms the web.config file does not exist. The question then arises of where to create a connection string to use in multiple forms without the necessity of supplying a connection string  in each from. The solution is to put the connection string in the app.config file in Windows Forms applications and access these connection strings in multiple forms.

Use the following procedure to create it.

Step 1

Open a Windows Forms application in Visual Studio 2010 and right-click on your application name within Solution Explorer then choose "Add" >> "New Item" >> "Application Configuration File".

add-new-item.jpg

application-configration-file.jpg

Step 2

Now the app.config file is added to your Windows Forms application where you can supply a connection string.

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

  <connectionStrings>

    <add name ="Myconnectionstring" connectionString ="Data Source=.;Initial Catalog=pulkit;User ID=sa;Password=Wintellect" />

  </connectionStrings>

</configuration>

 

Step 3

Now you can use this connection string in multiple Windows Forms. First add a reference to System.Configration and then write the code in the Windows Form.

using System.Configuration;

string connectionString = ConfigurationManager.ConnectionStrings["MyconnectionString"].ConnectionString;

 

Summary

In this article I have used a connection string in Widows Forms from an app.config file. In this way you can use a connection string in multiple forms.

Up Next
    Ebook Download
    View all
    Learn
    View all