Click here to Skip to main content
15,312,009 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I've declared a Friend Variable in my start up .aspx page. I've also tried declaring it as Public

Shouldn't I be able to access that variable all across the project?

This should be easy I know. But I'm missing something.

What I have tried:

Class _Default
    Inherits System.Web.UI.Page
     Friend testVar as string = "something"
End Class

In another .aspx page I try -
Public Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

Dim readtestVar = testVar

End Sub

Produces an error 'testVar is not declared. It may be inaccessible due to it's protection level.'
Updated 19-Jul-16 5:40am

1 solution

Friend does mean it is accessible - but it doesn't confer magical powers upon it!
Let's ignore computers for a moment, and look at cars. You put your mobile phone in the glove box of your car, and lock it in. You - as a friend - give me the key to your glove box. Does that mean I can use it to unlock the glove box in my car and retrieve your mobile? No - because the glove box that contains the phone is part of your car, not mine.
Friend in VB works the same way - it requires the right instance of a car in order to access the glove box. Since the instance is in a different page, you can't easily get to the page, let alone get access to it's Friend variables.

Instead of this, move it to the Session and access it there - that is exactly what the Session is there for!
Member 12637386 19-Jul-16 11:45am
Thanks. But I still need a Public variable that is accessible across different pages/routines.

I've tried declaring it as Public, and I get the same error.
OriginalGriff 19-Jul-16 11:53am
Because Public does the same thing: it's an access modifier, it doesn't magically make it not require an instance.
There is something that does that: Shared - but that is very very dangerous in a website as it creates a single variable that is common to the whole app. But...many users of your site will share the same app and thus the same variable, so it may not contain what you think it should!
Seriously: use the Session.
Member 12637386 19-Jul-16 12:15pm
Yes, I want the variable to be unique to the user. I've never even heard of a session variable and am looking for info online. Any boost on where to declare this would be a help. Again, it needs to be unique to the user, and available across different .aspx pages.
OriginalGriff 19-Jul-16 12:20pm
Then the Session is the way to go (or cookies, but they are stored on the user computer)
Will give you everything you need.
Member 12637386 19-Jul-16 15:38pm
Thanks OriginalGriff. That will come in handy
OriginalGriff 19-Jul-16 16:29pm
You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900