Variable Scope & Page.DataBind()?

A

Arpan

The following code works fine:

<script runat="server">
Dim strName As String = "Arpan"
Sub Page_Load(ByVal obj As Object, ByVal ea As EventArgs)
Page.DataBind()
End Sub
</script>

<form runat="server">
<asp:Label id="lblMessage" Text=<%# strName %> runat="server"/>
</form>

But if the line

Dim strName As String = "Arpan"

is placed inside the Page_Load sub so that the script code looks like
this:

<script runat="server">
Sub Page_Load(ByVal obj As Object, ByVal ea As EventArgs)
Dim strName As String = "Arpan"
Page.DataBind()
End Sub
</script>

then the following error gets generated:

Name 'strName' is not declared.

pointing to the line

<asp:Label id="lblMessage" Text=<%# strName %> runat="server"/>

Why so?

Thanks,

Arpan
 
G

Guest

Why not just have a line like

lblMessage.Text = strName

In your Page_Load event handler.
 
A

Arpan

clickon, I very well am aware of the fact that it can be done in the
way you have shown which, I believe, is the easiest way out but being a
newbie as far as DataBinding is concerned (which I thought goes without
saying since had I not known that simple 1-line code that you have
shown which any ASP.NET newbie learns at the very beginning, I don't
think I, or for that matter, any newbie, would have posted this basic
question on DataBinding), I did like to grasp the fundamentals of
DataBinding.

Moreover I am not asking for any alternative code; rather I did like to
know why the error.gets generated when the variable "strName" is
declared & assigned a value in the Page_Load sub.

Arpan
 
A

ashish

Arpan,

when you declare a variable inside a page load event handler, its not a
member of page class, so when asp.net generates c# code for your there
is no variable named strName, and hence is complains.

Following line of code would look for a protected (private if not using
code behind model) property/variable named strName in your page class

<asp:Label id="lblMessage" Text=<%# strName %> runat="server"/>

hth
 
A

Arpan

Thanks, Ashish, for your response.

What about variables declared within subs (be it user-defined or
built-in) other than the Page_Load sub - aren't they members of the
Page class as well? If yes, does that mean variables declared within
the <script runat="server"> tag but outside any sub automatically
become members of the Page class?

Thanks,

Regards,

Arpan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

ListBox? 2
Dynamically Populate Server Control? 5
System.IO? 9
Request.Form 1
Label Control? 8
ViewState Variable Vs. Session Variable 2
OnItemCommand & OnItemDataBound 2
ViewState/StateBag? 1

Staff online

Members online

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,045
Latest member
DRCM

Latest Threads

Top