Why Can't This Be Done?

  • Thread starter Thread starter rn5a
  • Start date Start date
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?
 
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.
 
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.
 
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...
 
Back
Top