2015-02-09 12 views
0

我已經使用visual studio 2010在vb.net winform中創建了一個簡單的表單(Name RapidSales)。我在此表單上有datagridview1。每當我使用下面的代碼調用它的成功運作: -創建和使用表單實例給出錯誤

RapidSales.rgv.CurrentRow.Cells("ProductId").Value = myvalue 

但每當我在這個「RapidSales」形式的實例創建並編寫和運行下面的代碼它給我一個錯誤:

Dim winform As New RapidSales() 
winform.rgv.CurrentRow.Cells("ProductId").Value = myvalue 

錯誤信息如下: -

Object reference not set to an instance of an object. 

請人幫忙,我怎樣才能避免這種錯誤,併成功運行我的代碼。

在此先感謝

+0

可能重複[什麼是空指針異常,以及如何解決它?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do -i-fix-it) – 2015-02-09 11:12:26

+1

更有可能這一個:[什麼是NullReferenceException,我該如何解決它?](http://stackoverflow.com/questions/4660142/wha t-is-a-nullreferenceexception-and-how-do-i-fix-it)。另一個是Java – Jcl 2015-02-09 11:13:02

回答

0

雖然在它的心臟,這是另一個NullReference Exception這看上去有多您正在使用的形式引用有關。這個問題沒有提供很多背景,因此涉及到一些猜測。

Dim winform As New RapidSales() 
winform.rgv.CurrentRow.Cells("ProductId").Value = myvalue 

用在僅僅是這樣,winformRapidSales形式的實例;它不是對RapidSales的任何現有默認實例的對象引用。在這一點上,rgv控件(DGV?)幾乎不可能有任何行,所以NRE通過引用這些空對象而得到結果。

如果RapidSales.rgv.CurrentRow.Cells("ProductId").Value = myvalue作品,則意味着窗體的默認實例已經創建並可能顯示了要填充的控件等,你可能想是這樣的:

' module/class/form level variable for the other form 
Private winform As RapidSales 

'... elsewhere when it is needed: 
If winform Is Nothing   ' test if already instanced 
    winform = New RapidSales() 
    ' other setup stuff 
End If 
winform.Show()    

' else where use it: 
Sub Something(myvalue As Integer)   ' no idea of the Type 
    winform.rgv.CurrentRow.Cells("ProductId").Value = myvalue 
    ... 
End Sub 

更多關於explicit form instances