在这个程序(VB,ASP.NET 2010)创建三个字段:accno
,name
和balance
,以及以下按钮:create
,destroy
,set
和get
。 但是,当点击set
或get
方法它提供了以下异常:object reference not set to an instance of an object
如何解决“未将对象引用设置为对象实例”的错误?
Default.aspx.vb
Partial Class _Default
Inherits System.Web.UI.Page
Dim obj As account 'declaring the obj of class account
Protected Sub btn_create_Click(sender As Object, e As System.EventArgs) Handles btn_create.Click
obj = New account 'initializing the object obj on class accounts
End Sub
Protected Sub btn_set_Click(sender As Object, e As System.EventArgs) Handles btn_set.Click
'sending the values from textboxes to accounts class through method setdata
Try
obj.setdata(CInt(txt_accno.Text), (txt_name.Text), CInt(txt_bal.Text))
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Protected Sub btn_get_Click(sender As Object, e As System.EventArgs) Handles btn_get.Click
'calling the method getdata to view the output
Try
obj.getdata()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Protected Sub btn_destroy_Click(sender As Object, e As System.EventArgs) Handles btn_destroy.Click
'calling the constructor
obj = Nothing
End Sub
End Class
Account.vb
Imports Microsoft.VisualBasic
Public Class account
Private accno As Integer
Private acc_name As String
Private bal As Integer
'constructor
Public Sub New()
MsgBox("object created")
End Sub
'public method to populate above three private variable
Public Sub setdata(ByVal a As Integer, ByVal b As String, ByVal c As Integer)
Me.accno = a
Me.acc_name = b
Me.bal = c
End Sub
Public Sub getdata()
MsgBox(Me.accno.ToString + vbNewLine + Me.acc_name + vbNewLine + Me.bal.ToString)
End Sub
'destructor
Protected Overrides Sub finalize()
MsgBox("object destroyed")
End Sub
End Class
你为什么喊?你的键盘似乎没问题。 –
我希望所有这些'MsgBox's仅用于临时调试 - 您知道它们只在使用开发服务器运行时工作,甚至在它们工作时运行,然后在服务器上运行,而不是(必然)在同一台机器上运行该网页正在显示。 –
几乎所有的'NullReferenceException'都是一样的。请参阅“[什么是.NET中的NullReferenceException?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net)”的一些提示。 –