9

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?

5 Answers 5

8

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.

Sign up to request clarification or add additional context in comments.

1 Comment

What are the advantages of declaring a property instead of a field? I don't see any if there is no logic necessary for get and/or set.
1

Use the protected modifier.

Protected test As String = "test"

1 Comment

do you have more info on this?
0

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.

Comments

0

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.

Comments

0

Declare variable either protected or public:

Protected  test As string = "test"

And in .aspx file:

<%=test%>

1 Comment

Welcome to Stack Overflow. Please read Stack Overflow: How to answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.