none
Why am I getting an error::System.NullReferenceException: 'Object reference not set to an instance of an object.' RRS feed

  • Question

  • I have a form; form1 that looks like this:
    Imports System.Data.SqlClient
    Public Class form1
        Public gs_SQL_CS_RecordManagement As String = "SERVER=techdev01;DATABASE=DB02_RECORD_MANAGEMENT;USER ID=db02;PASSWORD=db02;"
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            Call RefreshDGV()
        End Sub
    
        Public Sub RefreshDGV()
            If Me.InvokeRequired() Then
                Me.Invoke(Sub() RefreshDGV())
            Else
                MsgBox("refesh dgv")
    
                Dim dgv_rec As New DataGridView
                Dim qry As String = "select recd_id, recd_number, recd_inventorydate from t021400_records order by recd_number desc;"
                Dim cs As String = gs_SQL_CS_RecordManagement
                Try
                    Dim connectionString As String = cs
                    Dim connection As New SqlConnection(connectionString)
                    Dim dataadapter As New SqlDataAdapter(qry, connection)
                    Dim ds As New DataSet()
                    connection.Open()
                    dataadapter.Fill(ds, "dgv")
                    ' dataadapter.Fill(ds)
                    connection.Close()
                    dgv_records.DataSource = DBNull.Value
                    dgv_records.DataSource = ds
                    dgv_records.DataMember = "dgv"
    
                    With dgv_records
                        .RowsDefaultCellStyle.BackColor = Color.Bisque
                        .AlternatingRowsDefaultCellStyle.BackColor = Color.Beige
                    End With
    
                Catch EX As Exception
                    MsgBox(EX.ToString & " - (SQLRoutines-ReadT010200_MyManagementTeam)")
                    Exit Sub
                End Try
            End If
        End Sub
    
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Form2.Show()
        End Sub
    End Class
    When I press button1 form2 is called. It looks like this:

    Public Class Form2 Private _form1 As Form1 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Me._form1.RefreshDGV() End Sub End Class

    When I press button1 on form2 I get an error message:

    me._form1.RefreshDGV() -System.NullReferenceException: 'Object reference not set to

    an instance of an object.'

    Why do I get this error?

    Tuesday, February 27, 2018 6:49 PM

Answers

  • It works as expected.  It is amazing what one line of code will do. Thank you very much.  

    SC

    • Marked as answer by sclarkx Wednesday, February 28, 2018 12:52 PM
    Wednesday, February 28, 2018 12:52 PM

All replies

  • I have a form; form1 that looks like this:
    Imports System.Data.SqlClient
    Public Class form1
        Public gs_SQL_CS_RecordManagement As String = "SERVER=techdev01;DATABASE=DB02_RECORD_MANAGEMENT;USER ID=db02;PASSWORD=db02;"
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            Call RefreshDGV()
        End Sub
    
        Public Sub RefreshDGV()
            If Me.InvokeRequired() Then
                Me.Invoke(Sub() RefreshDGV())
            Else
                MsgBox("refesh dgv")
    
                Dim dgv_rec As New DataGridView
                Dim qry As String = "select recd_id, recd_number, recd_inventorydate from t021400_records order by recd_number desc;"
                Dim cs As String = gs_SQL_CS_RecordManagement
                Try
                    Dim connectionString As String = cs
                    Dim connection As New SqlConnection(connectionString)
                    Dim dataadapter As New SqlDataAdapter(qry, connection)
                    Dim ds As New DataSet()
                    connection.Open()
                    dataadapter.Fill(ds, "dgv")
                    ' dataadapter.Fill(ds)
                    connection.Close()
                    dgv_records.DataSource = DBNull.Value
                    dgv_records.DataSource = ds
                    dgv_records.DataMember = "dgv"
    
                    With dgv_records
                        .RowsDefaultCellStyle.BackColor = Color.Bisque
                        .AlternatingRowsDefaultCellStyle.BackColor = Color.Beige
                    End With
    
                Catch EX As Exception
                    MsgBox(EX.ToString & " - (SQLRoutines-ReadT010200_MyManagementTeam)")
                    Exit Sub
                End Try
            End If
        End Sub
    
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Form2.Show()
        End Sub
    End Class
    When I press button1 form2 is called. It looks like this:

    Public Class Form2 Private _form1 As Form1 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Me._form1.RefreshDGV() End Sub End Class

    When I press button1 on form2 I get an error message:

    me._form1.RefreshDGV() -System.NullReferenceException: 'Object reference not set to

    an instance of an object.'

    Why do I get this error?

    Because you never assign an instance of Form1 to the variable _form1.

    You need to add a constructor or public property that you can set from Form1 when you create or show Form2.  For example

    Public Class Form2
       private _form1 As Form1
    
       Public Sub New(form1Instance As Form1)
          _form1 = form1Instance
       End Sub
    ...
    End Class

    Then in Form1 you would do:

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Dim f As New Form2(Me)
            f.Show()
        End Sub
    Your current button click code in Form1 is showing the default instance of Form2.  Do not use default form instances.  They were for VB6 upgrade compatibility and should not be used directly in code you write.  Always create an explicit instance of the form to work with.


    Reed Kimble - "When you do things right, people won't be sure you've done anything at all"

    Tuesday, February 27, 2018 7:05 PM
    Moderator
  • Please bare with me, but all I get when I press the button on form1 is an empty screen.  What is wrong?
    Tuesday, February 27, 2018 8:35 PM
  • all I get when I press the button on form1 is an empty screen.  What is wrong?

    What do you believe should have happened?   Is Form2 an empty screen, or is it something else?

    What is the code you are currently using for the button click?

    Tuesday, February 27, 2018 8:43 PM
  • Here is what I want to do:

    Modify  a program that will display a data grid view (dgv) from a SQL table in form1. There are some fields in the dgv to do searches on. I want the user to start form2 and enter the search criteria, then press a button that will invoke the subroutine written in form1 I have this working except I cannot get the dgv subroutine in form1 to  run in form2.  

    I wrote a smaller program to test my theory and here it is.

    Form has on it a dgv and a button to invoke form2. Form2 has a button to run the the subroutine in form1. 

    Here is the entire code:

    Form1

    Imports System.Data.SqlClient
    Public Class form1
        Public gs_SQL_CS_RecordManagement As String = "SERVER=techdev01;DATABASE=DB02_RECORD_MANAGEMENT;USER ID=db02;PASSWORD=db02;"
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            Call RefreshDGV()
        End Sub
    
    
    
        Public Sub RefreshDGV()
            If Me.InvokeRequired() Then
                Me.Invoke(Sub() RefreshDGV())
            Else
                'MsgBox("refesh dgv")
    
                Dim dgv_rec As New DataGridView
                Dim qry As String = "select recd_id, recd_number, recd_inventorydate from t021400_records order by recd_number desc;"
                Dim cs As String = gs_SQL_CS_RecordManagement
                Try
                    Dim connectionString As String = cs
                    Dim connection As New SqlConnection(connectionString)
                    Dim dataadapter As New SqlDataAdapter(qry, connection)
                    Dim ds As New DataSet()
                    connection.Open()
                    dataadapter.Fill(ds, "dgv")
                    ' dataadapter.Fill(ds)
                    connection.Close()
                    dgv_records.DataSource = DBNull.Value
                    dgv_records.DataSource = ds
                    dgv_records.DataMember = "dgv"
    
                    With dgv_records
                        .RowsDefaultCellStyle.BackColor = Color.Bisque
                        .AlternatingRowsDefaultCellStyle.BackColor = Color.Beige
                    End With
    
                Catch EX As Exception
                    MsgBox(EX.ToString & " - (SQLRoutines-ReadT010200_MyManagementTeam)")
                    Exit Sub
                End Try
            End If
        End Sub
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Dim f As New Form2(Me)
            f.Show()
        End Sub
    End Class

    Form2:

    Public Class Form2
        Private _form1 As Form1
        Public Sub New(form1Instance As Form1)
            _form1 = form1Instance
        End Sub
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Me._form1.RefreshDGV()
        End Sub
    
        Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    
        End Sub
    

    Tuesday, February 27, 2018 9:08 PM
  • Form has on it should be forn1
    Tuesday, February 27, 2018 9:11 PM
  • Sorry, you pasted in my code example instead of typing it and I typed it in the web browser directly.

    Your constructor needs to call InitializeComponent.  This line of code would be added automatically if you had typed "Public Sub New(form1Instance As Form1)" and pressed enter.  So the actual constructor should look like:

    Private _Form1 As Form1
    Public Sub New(form1Instance As Form1)
    
        ' This call is required by the designer.
        InitializeComponent()
    
        ' Add any initialization after the InitializeComponent() call.
        _Form1 = form1Instance
    End Sub
    


    Reed Kimble - "When you do things right, people won't be sure you've done anything at all"

    Tuesday, February 27, 2018 9:19 PM
    Moderator
  • Hi sclarkx,

    According to your description, you have two Form, one is Form1, another is Form2, you want to click Button in Form2 to show Form1, because RefreshDGV method is called in Form1_load event, so you just do Form1.show.

     Public Class Form2
    
            Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
                Dim _form1 As New Form1
                _form1.Show()
            End Sub
    
            Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    
            End Sub

    Best Regards,

    Cherry


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Proposed as answer by Mr. Monkeyboy Wednesday, February 28, 2018 3:49 AM
    Wednesday, February 28, 2018 2:37 AM
    Moderator
  • It works as expected.  It is amazing what one line of code will do. Thank you very much.  

    SC

    • Marked as answer by sclarkx Wednesday, February 28, 2018 12:52 PM
    Wednesday, February 28, 2018 12:52 PM
  • It works as expected.  It is amazing what one line of code will do. Thank you very much.  

    SC

    Glad you got it working.

    When using this forum you normally click the Mark as answer link on the post or posts that solved the problem, rather than the final comment of the thread.  You can update the answers in the thread if you'd like.


    Reed Kimble - "When you do things right, people won't be sure you've done anything at all"

    Wednesday, February 28, 2018 1:22 PM
    Moderator