views:

67

answers:

3

How do declare a public variable .aspx web page that can be used in all the pages within my web application?

And/or create a Public Sub?

A: 

A public sub, assuming you use VB:

Public Sub MyOwnSub()
   'do something'
End Sub

A global variable: add a module to your VB and add a variable to that module. You can call that variable with ModuleName.VariableName from everywhere.

When you declare a public variable in the code-behind of your ASPX page, and you declare it shared, you can access it with YourPageName.VariableName from anywhere in your web application. Note that this variable is shared between all processes or requests.

Public Shared VariableName As String = "hello world"
Abel
Thanks Abel, it work fine. U r the man
CHUKS EKE
@CHUKS EKE: thanks. If indeed so, you're free to vote for questions here that helped you, or accept an answer that best answers your question. Also, see [FAQ](http://stackoverflow.com/faq) and welcome at SO!
Abel
A: 

You can use Session or Application state to hold global data needed for your website.

  • Session object is created per user and expires after some time(do not remember how much)
  • Application object is created when application started and will persist as long as application is running.
Alex Reitbort
By default, a session expires after 20 minutes of inactivity, but you can set this timeout in `web.config`.
Abel
A: 

Maybe you can work with ViewState to persist values into the session.

I think that isn't possible to create 'global variables', since the value is lost at every page load...

ViewState["key"] = variable;

variable = ViewState["key"];
Kira
`ViewState` should be used at control-level, in pages, it is better to use sessions. Don't forget to cast the returned value of `ViewState[]`.
Abel