HTML clipboardIntroduction and Demonstration
Connection strings are typically stored in web.config, and usually meant the
appSettings section. Here is a example of connectin string which exist in config
file.
<connectionStrings>
<add
name="AppServiceName"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User
Instance=true"
providerName="System.Data.SqlClient"/>
</connectionStrings>
Although the providerName attribute isn't compulsory, connection strings won't
appear in the Configure Data Source dialogs without a provider name being set.
Within applications, we can access these connection strings in two ways. In
code, we use the ConnectionStrings property of the ConfigurationManager object.
For example:
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
ConfigurationManager.ConnectionStrings["AppServiceName
"].ConnectionString;
The ConnectionStrings property contains a collection of the connection strings
from the section in web.config, so we use the name property as the index to the
collection. The ConnectionString property then returns the actual connection
string.
Within the markup of ASP.NET pages, we use an expression builder, which is a new
feature of ASP.NET 2.0. Expression builders allow we to declaratively access
features such as connection strings, application settings, and resources. For
example, consider the following code:
<asp:SqlDataSource id="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:AppServiceName %> "
The expression builder uses a server side <% %> block, but when the first
character within that block is a $ sign this indicates an expression builder is
to be used. Each expression builder has a known prefix, and for connection
strings this is ConnectionStrings. In a similar method to code, we use the name
attribute from the web.config section to identify the required connection
string, using a : to separate the builder prefix from the name.
The beauty of these two methods is that from both code and markup we can use the
centrally stored connection strings.
Conclusion
I hope this article will help you to place connection string in web pages.
HAVE A HAPPY CODING!