Hi Chen,
Here's something I use in C# that reduces the connectioin string code in an ASP.NET page to the following line:
OleDbConnection cn = new OleDbConnection(GlobalStatics.ConnectionString);
Here's how it works. I'm using a secured .mdb with a work group file named system.mdw just to cover all the bases. Both db's are on the server.
1. File: Global.asax.cs
Add the following to the Application_Start sub in global.asax -
Code:
protected void Application_Start(Object sender, EventArgs e)
{
string connectString = ConfigurationSettings.AppSettings["ConnectionString"];
connectString = String.Format(connectString, Server.MapPath("ArabianNights.mdb"), Server.MapPath("system.mdw"));
Globals.ConnectionString = connectString;
}
2. File: GlobalStatics (User-defined class)
Since C# doesn't support
VB style global variables, create a new class and call it GlobalStatics. Create a static read/write property to store the connection string. Here's the code:
Code:
using System;
namespace AccessGlobalConnCS
{
// A sealed class cannot be inherited.
public sealed class GlobalStatics
{
private static string connectionString;
public static string ConnectionString
{
get { return connectionString; }
set { connectionString = value; }
}
private GlobalStatics()
{
//*********************************************************
//
// Since this class provides only static connection
// string get/set methods, make the default constructor
// private to prevent instances from being created with
// "new GlobalStatics()".
//
//*********************************************************
}
}
}
3. File: Web.config
Here's the <appsettings> attribute:
Code:
configuration>
<appSettings>
<add key="ConnectionString"
value="Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Jet OLEDB:System Database={1};User ID=Ali Baba;Password=Open sesame "/>
</appSettings>
4. File: WebForm1.aspx.cs
Open connections on the WebForm code-behind file like:
Code:
private void Page_Load(object sender, System.EventArgs e)
{
//Pass connection string to OleDbConnection object.
OleDbConnection cn = new OleDbConnection(GlobalStatics.ConnectionString);
//Open connection.
cn.Open();
//Pass SQL statement to OleDbCOmmand object.
string selectString = "SELECT MagicalFormulaID, MagicalFormulaName FROM MagicalFormulas";
OleDbCommand cmd = new OleDbCommand(selectString,cn);
//Execute an OleDbDataReader
OleDbDataReader reader = cmd.ExecuteReader();
//Bind DataReader to DataGrid
DataGrid1.DataSource = reader;
DataGrid1.DataBind();
//Close reader and connection.
reader.Close();
cn.Close();
}
Probably should use encrypted passwords in WebConfig files, but you get the general idea. Just using a C# static property to emulate a
vb global variable.
- Bob