Why Can't This Be Done?

R

rn5a

Assume that a Web Form has a TextBox server control whose ID is
*txtName*. Now why can't I do something like this?

<script language="VB" runat="server">
Dim txtName As String = txtName.Text

'other subs & functions come here
</script>

The above code generates the following error pointing to the very
first line within the <script></script> tags:

Object reference not set to an instant of an object.

What causes this error? Is it because at that point, the TextBox
hasn't been created yet on the Form?
 
?

=?ISO-8859-1?Q?G=F6ran_Andersson?=

Assume that a Web Form has a TextBox server control whose ID is
*txtName*. Now why can't I do something like this?

<script language="VB" runat="server">
Dim txtName As String = txtName.Text

'other subs & functions come here
</script>

The above code generates the following error pointing to the very
first line within the <script></script> tags:

Object reference not set to an instant of an object.

What causes this error? Is it because at that point, the TextBox
hasn't been created yet on the Form?

You have declared a local variable with the same name as the control, so
the control is not visible at all in that scope. You are trying to get
the value for the string from the (non-existent) Text property of the
same string, which gives you a null reference error as the reference has
yet not been set.
 
?

=?ISO-8859-1?Q?G=F6ran_Andersson?=

Eliyahu said:
hmm... If you are right, I would expect a compiler error for non-existent
property Text...

Yes, you would. That is also exactly what I get when I try your code. I
can not explain why you are not getting that.
 
M

Mark Rae

hmm... If you are right, I would expect a compiler error for non-existent
property Text...

Would that not be the case only if Option Strict was on...? Can't be sure
about this - never go anywhere near VB.NET if I can possibly help it...
 

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

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,226
Members
46,815
Latest member
treekmostly22

Latest Threads

Top