Jorre
Jorre

Reputation: 17591

asp.net pass variable from code behind to .aspx

I guess I'm missing something here, but I can't find a way to pass a simple variable from my code behind file to the .aspx page.

In code behind I have:

Dim test As String = "test"

and in my aspx page I try: <%=test %>

that gives me the following error: Error 2 'test' is not declared. It may be inaccessible due to its protection level

Am I forgetting something here?

Upvotes: 9

Views: 39552

Answers (5)

Aman
Aman

Reputation: 1

Declare variable either protected or public:

Protected  test As string = "test"

And in .aspx file:

<%=test%>

Upvotes: 0

Ahmad Mageed
Ahmad Mageed

Reputation: 96557

Declare test as a property (at the class level) instead of a local variable, then refer to it as you currently do in your markup (aspx).

VB.NET 10 (automatic properties):

Protected Property test As String = "Test" 

Pre-VB.NET 10 (no support for automatic properties)

Private _test As String
Protected Property Test As String
Get
     Return _test
End Get
Set(value As String)
     _test = value
End Set
End Property

With the property in place you should assign a value to it directly in your code-behind.

Upvotes: 8

Max Toro
Max Toro

Reputation: 28618

Use the protected modifier.

Protected test As String = "test"

Upvotes: 1

barrylloyd
barrylloyd

Reputation: 1589

Try changing it to...

Public test As String = "test"

then it should work.

From here http://msdn.microsoft.com/en-us/library/76453kax.aspx ...

At the module level, the Dim statement without any access level keywords is equivalent to a Private declaration. However, you might want to use the Private keyword to make your code easier to read and interpret.

Upvotes: 0

shahkalpesh
shahkalpesh

Reputation: 33474

Change the code to

Protected test As String = "test" (in .vb file)

<%=Me.test%> (inside the markup)

EDIT: As suggested by @Ahmed, it is better to create a property instead of a variable such as the one I have provided.

Upvotes: 0

Related Questions