By: John Kilgo Date: November 28, 2002 Download The Code.
Printer Friendly Version
Here we present an example of how to store a database connection string in the application's Web.Config file. Web.Config is a part of every asp.net application and provides a nice, central location for storing information that may be needed in many of .................... ..
<% 'Program: ConnString.aspx' By: John Kilgo 'Date: November 28, 2002' CodeBehind: ConnString.aspx.vb 'Purpose: Demonstrates using Web.Config to hold a connection string' and reading that string from a program% > <% @ Page Inherits = "Connstring" src = "Connstring.aspx.vb"%>
Next is the code-behind page which accesses the Web.Config file to obtain the database connection string. Notice that we must Import the namespace System.Configuration in order to access the Web.Config file. Web.Config (shown after the .vb code) contains a key-value pair which specifies a key of "ConnectionString" with a value which is the connection string. We set a string variable ( "strConnection") equal to ConfigurationSettings.AppSettings ( "ConnectionString"). We have now captured the connection string for use in our program.Imports SystemImports System.WebImports System.Web.UIImports System.Web.UI.WebControlsImports System.DataImports System.Data.SqlClientImports System.ConfigurationPublic Class ConnString: Inherits Page Protected dataGrid As dataGrid Protected Sub Page_Load ( Byval e AS Object, BYVAL E as Eventargs DIM SQLCONN AS SQLCONNECTION DIM SQLCMD AS SQLCOMMAND DIM STRCONNECTION AS STRING TRY 'GET Connection String from Web.Config Strconnection = ConfigurationSettings.AppSettings ( "ConnectionString") sqlConn = New SqlConnection (strConnection) sqlCmd = New SqlCommand ( "SELECT * FROM Customers WHERE" _ & "(CompanyName LIKE 'A%') OR (CompanyName LIKE 'B%')", sqlConn) sqlConn.Open () dataGrid.DataSource = sqlCmd.ExecuteReader () dataGrid.DataBind () Catch ex As Exception Response.Write (ex.ToString & "
") Finally sqlConn.Close () End Try End SubEnd Class
.....................
XML Version = "1.0" encoding = "UTF-8"?>