In this article, I will explain how to create a one-time connection string in a Windows Forms form without using ConfigurationManager properties. Suppose you want to create a connection string in the app.config file. Then what are the steps required for that? Let us keep this simple. First we add a connection string in the app.config file. Then we write simple code as in the following:
<add name="connectionstr" connectionString="Data Source=MCNDESKTOP43;Initial Catalog=EmpDetail;Persist Security Info=True;User ID=sa;Password=*****"
Then what we do in the C# page is we just add a namespace "using System.Configuration;" and we write the following code:
string connstr = ConfigurationManager.ConnectionStrings["connectionstr"].ToString();
The string variable named "connstr" will then have the connection string.
For example: SqlDataAdapter da = new SqlDataAdapter("sql auery",connstr);
Note that most experienced programmers prefer to use this approach. Use the following procedure.
Open Visual Studio 2012 and click "File" -> "New" -> "Project...". A window is opened. In this window, click Windows Forms Application under Visual C#.
Give the name of your application as "ConnectionString" and then click OK.
After Step 1, a new window is opened on the right side. This window is called the Solution Explorer. The Solution Explorer contains the properties, App.config file, References, Form1.cs file and Program.cs file as in the following:
Just go to the "Properties" node then double-click on "Settings.Settings". You will then get a grid with columns for Name, Type, Scope and Value as in the following:
Now, specify a name, then click in the Type cell. In the drop-down box choose "Connection String". Then set the Scope to "Application".
Then click in the value cell and an ellipsis ("...") will appear in the right. Click on the ellipsis and create the connection string.
Then in the program, access (use) the connection string using: Properties.Setting.Default.(name) where (name) is the name you provided in the name column.
In this example, we will display a record in a DataGridView on a button click.
You see that the Connection String is automatically included..
<?xml version="1.0" encoding="utf-8" ?>
<add name="ConnectionString.Properties.Settings.connection" connectionString="Data Source=MCNDESKTOP43;Initial Catalog=EmpDetail;Persist Security Info=True;User ID=sa;Password=*****"
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />