Access to an object created in page from a class
I have a page, Default.aspx, with its own code-behind file like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
开发者_开发百科 using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
public int[] anArray;
...
}
What I'd like to do is access to "anArray" from a C# class (not tied to a page) declared in \App_Code folder. What can I do?
Thanks.
Edit: As said in the first comment, I really apreciate your suggestions about refactoring my connection objects. However, what I'm really doing here is to rewrite an old PHP application in order to get comfortable with basic C# and ASP.NET, so this code will never go really live. So, I'm still intersted in a way (if any) to access an object declared in a code-behind code from a standard C# class.
Edit2: I removed the OdbcConnection object in order to focus to the real problem: how to refer to an object istantiated in a code-behind file from a C# class situated in \App_Code?
That connection property will be accessible as
_Default.connection
from your class.
Just as an aside, this doesn't seem like a good approach. There are problems with using a static connection object - you will run into threading issues, and it seems like a poor place to actually declare the connection. You might want to consider refactoring your connection object into an actual class and have your page access it, instead of the other way around.
I'm with womp. Moreover, OdbcConnection
implements IDisposable
. Making it static and publicly available could make it's cleanup a nightmare.
Its a bad idea to use a static connection object.
You'll lose your connection periodically, and its hard to debug.
Instead, look at the Enterprise Library Data Access Block and take advantage of Automatic Connection Pooling. This will be the single greatest change you can make regarding database performance.
Its very easy to use, and will make calling stored procedures, etc MUCH easier for you, while providing better performance.
See this link for more information on using the Data Access Block of the Enterprise Library.
Here is another link that will help you get started. and here is a link to the download page
The problem is the you are adding classes to the APP_Code folder. Generally, these are not compiled in with the website, but are compiled into their own dll which is referenced by the Website dll.
Generally, what I do, since I hate that little caveat, is create a folder in the Website project called Code, and use that instead of the App_Code folder.
Out of curiosity, what version of Visual Studio are you using?
精彩评论