0

I have created a simple form (Name RapidSales) in vb.net winform using visual studio 2010. I have datagridview1 on this form. Whenever i call to it by using the following code its successfully works:-

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

But whenever i create in instance of this 'RapidSales' form and then write and run the following code it gives me an error:

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

Error message is following:-

Object reference not set to an instance of an object.

Please anyone help that how can i avoid this error and run my code successfully.

Thanks in advance

user3004110
  • 929
  • 10
  • 24
  • 36
  • possible duplicate of [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it) – Tony Hopkinson Feb 09 '15 at 11:12
  • 1
    More likely this one: [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) . The other one is for Java – Jcl Feb 09 '15 at 11:13

1 Answers1

0

While at its heart, this is another NullReference Exception it seems related to how you are using the form reference. The question does not provide much context, so some guesswork is involved.

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

Used in just that way, winform is a new instance of the RapidSales form; it is not an object reference to any existing default instance of RapidSales. It is very unlikely that the rgv control (a DGV?) has any rows at all at this point, so the NRE results from referencing those null objects.

If RapidSales.rgv.CurrentRow.Cells("ProductId").Value = myvalue works, it means that the default instance of the form is already created and likely shown for the controls to be populated etc. You probably want something like this:

' 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

More on explicit form instances

Community
  • 1
  • 1
Ňɏssa Pøngjǣrdenlarp
  • 38,411
  • 12
  • 59
  • 178