此VB.NET错误是什么意思? “对象引用未设置为对象的实例”

问题描述

我有三个sql表:TGolfers,TEventYears和TGolferEventYears。 TGolferEventYears是一个表,说明高尔夫球手在哪个事件中打过球。我已经成功填充了Event Years组合框(cboEventYears),现在我正尝试根据所选年份的高尔夫球手填充第二个Golfers组合框。但是由于某种原因,我的SELECT语句抛出错误:“对象引用未设置为对象的实例。”
我不知道那是什么意思,有人可以帮忙吗?下面的代码,谢谢。

'Load golfers combo Box based on event year
Private Sub cboEventYears_SelectedindexChanged(sender As Object,e As EventArgs) Handles cboEventYears.SelectedindexChanged

    Try

        Dim strSelect As String = ""
        Dim cmdselect As OleDb.OleDbCommand 'Used for Select Statement
        Dim drSourceTable As OleDb.OleDbDataReader 'Where data is retrieved to
        Dim dt As DataTable = New DataTable 'Table we will load from our reader

        'Open the DB
        If OpenDatabaseConnectionsqlServer() = False Then

            'If not,warn user
            MessageBox.Show(Me,"Database connection error." & vbNewLine &
                                    "The application will Now close.",Me.Text + " Error",MessageBoxButtons.OK,MessageBoxIcon.Error)

            'Close form
            Me.Close()
        End If

        'Build Select Statement 
        strSelect = "SELECT TGolfers.intGolferID,TGolfers.strLastName FROM TGolferEventYears JOIN TGolfers ON TGolferEventYears.intGolferID = TGolfers.intGolferID WHERE TGolferEventYears.intEventYearID = " & cboEventYears.SelectedValue.ToString

        'Retrieve all records
        cmdselect = New OleDb.OleDbCommand(strSelect,m_conAdministrator)
        drSourceTable = cmdselect.ExecuteReader

        'Load Table from Data Reader
        dt.Load(drSourceTable)

        'Add item to Combo Box. We need golferID to be associated
        'with the last name in order to pull the rest of the data.
        'Binding column name to the combo Box display and value members.
        cboGolfers.ValueMember = "TGolfers.intGolferID"
        cboGolfers.displayMember = "TGolfers.strLastName"
        cboGolfers.DataSource = dt

        'Select first item in the list by default
        If cboGolfers.Items.Count > 0 Then cboGolfers.Selectedindex = -1


     Catch excError As Exception

         'Log and display error message
         MessageBox.Show(excError.Message)

     End Try
End Sub

解决方法

您很有可能在select语句中引用了一个空值,我想说cboEventYears.SelectedValue.ToString是您的罪魁祸首。再次尝试使用一个常量而不是常量的代码,看看是否可以解决。您也可以尝试cboEventYears.text,我注意到通常这是更好的选择。