Introduction
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:
<connectionStrings>
<add name="connectionstr" connectionString="Data Source=MCNDESKTOP43;Initial Catalog=EmpDetail;Persist Security Info=True;User ID=sa;Password=*****"
providerName="System.Data.SqlClient" />
</connectionStrings>
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.
Step 1
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.
Step 2
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:
Step 3
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:
Step 4
Now,
specify a name, then click in the Type cell. In the drop-down box
choose "Connection String". Then set the Scope to "Application".
Step 5
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.
Example
In this example, we will display a record in a DataGridView on a button click.
Coding
Form1.cs[Design]
Form1.cs
App.config
You see that the Connection String is automatically included..
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
</configSections>
<connectionStrings>
<add name="ConnectionString.Properties.Settings.connection" connectionString="Data Source=MCNDESKTOP43;Initial Catalog=EmpDetail;Persist Security Info=True;User ID=sa;Password=*****"
providerName="System.Data.SqlClient" />
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>
Output
No comments:
Post a Comment