Groups | Blog | Home
all groups > asp.net > february 2007 >

asp.net : Why Can't This Be Done?


rn5a NO[at]SPAM rediffmail.com
2/24/2007 9:28:52 PM
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?
Eliyahu Goldin
2/25/2007 12:00:00 AM
I think your guess is pretty close. You should put the code in one of the
events, like Page_Load, to fit it exactly in the page life cycle.

--
Eliyahu Goldin,
Software Developer & Consultant
Microsoft MVP [ASP.NET]
http://msmvps.com/blogs/egoldin
http://usableasp.net


[quoted text, click to view]

Göran_Andersson
2/25/2007 2:17:58 PM
[quoted text, click to view]

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.

--
Göran Andersson
_____
Eliyahu Goldin
2/25/2007 3:59:59 PM
hmm... If you are right, I would expect a compiler error for non-existent
property Text...

--
Eliyahu Goldin,
Software Developer & Consultant
Microsoft MVP [ASP.NET]
http://msmvps.com/blogs/egoldin
http://usableasp.net


[quoted text, click to view]

Mark Rae
2/25/2007 6:58:57 PM
"Eliyahu Goldin" <REMOVEALLCAPITALSeEgGoldDinN@mMvVpPsS.org> wrote in
message news:u5CW$UOWHHA.3592@TK2MSFTNGP03.phx.gbl...

[quoted text, click to view]

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...

Göran_Andersson
2/25/2007 7:50:24 PM
[quoted text, click to view]

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.

--
Göran Andersson
_____
AddThis Social Bookmark Button