Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Page_Unload

Status
Not open for further replies.

nnmmss72

Programmer
May 14, 2006
110
IR
I know that every new which i use cause i use the memory, so i have to free it up manually or wait until GC clean it up.

suppose i have created the connection to the sql database
SqlConnection myConnection;
which is Global and it is used in

private void Page_Load(object sender, System.EventArgs e)
{
String ConnInfo=ConfigurationSettings.AppSettings["ConnInfo"];
myConnection=new SqlConnection(ConnInfo);
if (!Page.IsPostBack)
BindPage();
}

so i want to close the myConnection in the Page_Unload
private void Page_Unload(object sender, System.EventArgs e)
{
myConnection.Close();
}

but when i debugged the page i couldn't trace that by unloading the page the Page_Unload is running

so i went through the code i found there is line for Page_load in InitializeComponent,so i added this in it also
this.Unload +=new System.EventHandler(this.Page_Unload);

but again it doesn't enter the Page_Unload
is there anything wrong with it?
 
if you declare a new instance of sqlconnection each time you use it then you don't need the global variable.

if instead you want exactly 1 instance of the connection object throughout your application you need a singleton object
Code:
public static class SqlConnectionSingleton
{
   private static readonly SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["myconnection"]);
   public static LoadBalancer GetSqlConnection()
   {
     return connection;
   }
}
then you can use it in code like this
Code:
SqlCommand cmd = new SqlCommand(SqlConnectionSingleton.GetSqlConnection());
cmd.text = ...
cmd.Parameters.Add(...);
...

Jason Meckley
Programmer
Specialty Bakers, Inc.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top