Results 1 to 4 of 4

Thread: [RESOLVED] Variable is used before it has been assigned a value. a null reference exception....

  1. #1

    Thread Starter
    PowerPoster
    Join Date
    Apr 2005
    Location
    Debug.Print
    Posts
    3,885

    Resolved [RESOLVED] Variable is used before it has been assigned a value. a null reference exception....

    Hi all,

    I have been trying to change my code from SQL to Stored Procedures and I am having some problems with my code. Been trying to figure it out for a few hours already and not sure what's going on. The Error is:

    Variable is used before it has been assigned a value. A null reference exception could result at run-time.
    I am getting this issue on two lines. Those being the following:
    vb Code:
    1. 'Refill the DataAdapter with new information obtained from the database.
    2. GetInformationDA.Fill(GetInformationDS, TableName)

    vb Code:
    1. 'Assign the database column name to the DisplayMember and ValueMember properties.
    2. .DisplayMember = ColumnName

  2. #2

    Thread Starter
    PowerPoster
    Join Date
    Apr 2005
    Location
    Debug.Print
    Posts
    3,885

    Re: Variable is used before it has been assigned a value. a null reference exception

    My code is:
    vb Code:
    1. <CLSCompliant(True)> Public Sub PopulateDropDownListFromDB_WithWhereClauseX1(ByVal cboName As Elegant.Ui.ComboBox, _
    2.                                                                                  ByVal PullProtectionTools As Boolean, _
    3.                                                                                  ByVal PullDispatcherConsultantNames As Boolean, _
    4.                                                                                  ByVal PullComputerType As Boolean, _
    5.                                                                                  ByVal IsDispatcher As Boolean, _
    6.                                                                                  ByVal IsConsultant As Boolean, _
    7.                                                                                  ByVal bUseAutoComplete As Boolean, _
    8.                                                                                  ByVal bUseSQLDistinct As Boolean, _
    9.                                                                                  ByVal GetDBConInfo As String, _
    10.                                                                                  Optional ByVal WhereClause1 As String = Nothing, _
    11.                                                                                  Optional ByVal WhereClause2 As Integer = 0)
    12.  
    13.         'Define some new string variables.
    14.         Dim TableName, ColumnName As String
    15.  
    16.         Try
    17.             'Create a new SQLCommand object.
    18.             Dim GetInformation As New SqlCommand
    19.  
    20.             'Start a new database connection.
    21.             Using SetDatabaseConnection As New SqlConnection(GetDBConInfo)
    22.                 'Open the database connection.
    23.                 SetDatabaseConnection.Open()
    24.  
    25.                 If PullProtectionTools = True Then
    26.                     'Set some string variables.
    27.                     TableName = "ProtectionTools"
    28.                     ColumnName = "ProgramName"
    29.  
    30.                     'Set some values to the SQLCommand object.
    31.                     With GetInformation
    32.                         .Connection = SetDatabaseConnection
    33.                         .CommandType = CommandType.StoredProcedure
    34.                         .CommandText = "sp_GetProtectionTools"
    35.                         .Parameters.AddWithValue("@ProtectionToolType", WhereClause2)
    36.                     End With
    37.                 ElseIf PullComputerType = True Then
    38.                     'Set some string variables.
    39.                     TableName = "ComputerType"
    40.                     ColumnName = "ComputerTypeName"
    41.  
    42.                     'Set some values to the SQLCommand object.
    43.                     With GetInformation
    44.                         .Connection = SetDatabaseConnection
    45.                         .CommandType = CommandType.StoredProcedure
    46.                         .CommandText = "sp_GetComputerType"
    47.                         .Parameters.AddWithValue("@Manufacturer", WhereClause2)
    48.                     End With
    49.                 ElseIf PullDispatcherConsultantNames = True Then
    50.                     'Set some string variables.
    51.                     TableName = "DispatcherConsultantNames"
    52.                     ColumnName = "DispatcherOrConsultantName"
    53.  
    54.                     If IsDispatcher = True _
    55.                     And Not IsConsultant = True Then
    56.                         'Set some values to the SQLCommand object.
    57.                         With GetInformation
    58.                             .Connection = SetDatabaseConnection
    59.                             .CommandType = CommandType.StoredProcedure
    60.                             .CommandText = "sp_GetDispatchers"
    61.                             .Parameters.AddWithValue("@Dispatcher", WhereClause1)
    62.                         End With
    63.                     ElseIf IsConsultant = True _
    64.                     And Not IsDispatcher = True Then
    65.                         'Set some values to the SQLCommand object.
    66.                         With GetInformation
    67.                             .Connection = SetDatabaseConnection
    68.                             .CommandType = CommandType.StoredProcedure
    69.                             .CommandText = "sp_GetConsultants"
    70.                             .Parameters.AddWithValue("@Consultant", WhereClause1)
    71.                         End With
    72.                     End If
    73.                 End If
    74.  
    75.                 'Create a new SQLDataAdapter and DataSet.
    76.                 Dim GetInformationDA As New SqlDataAdapter(GetInformation)
    77.  
    78.                 'Create a new DataSet.
    79.                 Dim GetInformationDS As New DataSet(GetInformation.CommandText)
    80.  
    81.                 'Set the Current Culture of the DataSet.
    82.                 GetInformationDS.Locale = CurrentCulture
    83.  
    84.                 'Clear the DataSet of any previously obtained database information.
    85.                 GetInformationDS.Clear()
    86.  
    87.                 'Refill the DataAdapter with new information obtained from the database.
    88.                 GetInformationDA.Fill(GetInformationDS, TableName)
    89.  
    90.                 With cboName
    91.                     'First check to see if any records.  If no records, add a default item.
    92.                     Dim GetInformationDT As DataTable = New DataTable
    93.  
    94.                     'Set the culture of the DataTable.
    95.                     GetInformationDT.Locale = CurrentCulture
    96.  
    97.                     'Assign the table to the DataTable.
    98.                     GetInformationDT = GetInformationDS.Tables(TableName)
    99.  
    100.                     'Fill the ComboBox.
    101.                     'Assign the database table to the DataSource property.
    102.                     .DataSource = GetInformationDS.Tables(TableName)
    103.  
    104.                     'See if the ComboBoxes are autocomplete or not.
    105.                     If bUseAutoComplete = True Then
    106.                         .AutoCompleteMode = AutoCompleteMode.SuggestAppend
    107.                         .AutoCompleteSource = AutoCompleteSource.ListItems
    108.                     End If
    109.  
    110.                     'Assign the database column name to the DisplayMember and ValueMember properties.
    111.                     .DisplayMember = ColumnName
    112.                     .ValueMember = ColumnName
    113.  
    114.                     If GetInformationDT.Rows.Count > 0 Then 'Has records.
    115.                         If .Editable = False Then 'Not editable.
    116.                             'Select a default option.
    117.                             .Text = "Please Select"
    118.                         Else
    119.                             'Set the DataSource to nothing because you cant edit if set to something.
    120.                             .DataSource = Nothing
    121.                             .Items.Add("[Please Add An Item]")
    122.                             .SelectedIndex = 0
    123.                         End If
    124.                     End If
    125.                 End With
    126.  
    127.                 'Close the database connection.
    128.                 SetDatabaseConnection.Close()
    129.             End Using
    130.         Catch ex As SqlException
    131.             'Show the end user a message if an error is generated.
    132.             MessageBox.Show("There was an error retrieving data from table name " & TableName & "." & vbNewLine & vbNewLine & _
    133.                             "We are going to prepopulate the dropdown menu with a default value; therefore, you can disregard the error." & vbNewLine & vbNewLine & _
    134.                             "We highly suggest that you click on the plus sign next to the dropdown menu to add some options of your own." & vbNewLine & vbNewLine & _
    135.                             "The reason why you got this error in the first place is:" & vbNewLine & _
    136.                             "No data items in the database " & TableName & " to pull." & vbNewLine & vbNewLine & _
    137.                             "The exception error is:" & vbNewLine & _
    138.                             ex.Message, _
    139.                             "Database Information Retrieval Issues.", _
    140.                             MessageBoxButtons.OK, _
    141.                             MessageBoxIcon.Error, _
    142.                             MessageBoxDefaultButton.Button1, _
    143.                             MessageBoxOptions.DefaultDesktopOnly, _
    144.                             False)
    145.  
    146.             'If no rows are returned to populate the ComboBox, this will return an error, prepopulate with [Please Add An Item]
    147.             With cboName
    148.                 .DataSource = Nothing
    149.                 .Items.Add("[Please Add An Item]")
    150.                 .SelectedIndex = 0
    151.             End With
    152.         Catch ex As InvalidOperationException
    153.             MessageBox.Show(ex.Message, _
    154.                             "Invalid Operation Exception.", _
    155.                             MessageBoxButtons.OK, _
    156.                             MessageBoxIcon.Error, _
    157.                             MessageBoxDefaultButton.Button1, _
    158.                             MessageBoxOptions.DefaultDesktopOnly, _
    159.                             False)
    160.         Catch ex As NullReferenceException
    161.             MessageBox.Show(ex.Message, _
    162.                             "Null Reference Exception.", _
    163.                             MessageBoxButtons.OK, _
    164.                             MessageBoxIcon.Error, _
    165.                             MessageBoxDefaultButton.Button1, _
    166.                             MessageBoxOptions.DefaultDesktopOnly, _
    167.                             False)
    168.         End Try
    169.     End Sub

  3. #3
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    41,930

    Re: Variable is used before it has been assigned a value. a null reference exception

    There are three objects on this line (88 in your last post), and it could be referring to any of them:
    GetInformationDA.Fill(GetInformationDS, TableName)
    ..however, the lines just before it assign values to GetInformationDA and GetInformationDS, and as they are not in an If block etc they must run - so it can't be either of those variables.

    TableName is given a value earlier on, but only within an If block - and it is entirely possible that none of your conditions will match, so the variable will not be given a value.

    To correct that, either add an Else clause with no conditions to give it a default value, or (shorter) set a default value in the declaration.


    The ColumnName variable has exactly the same issue.

  4. #4

    Thread Starter
    PowerPoster
    Join Date
    Apr 2005
    Location
    Debug.Print
    Posts
    3,885

    Re: Variable is used before it has been assigned a value. a null reference exception

    Quote Originally Posted by si_the_geek View Post
    There are three objects on this line (88 in your last post), and it could be referring to any of them:
    ..however, the lines just before it assign values to GetInformationDA and GetInformationDS, and as they are not in an If block etc they must run - so it can't be either of those variables.

    TableName is given a value earlier on, but only within an If block - and it is entirely possible that none of your conditions will match, so the variable will not be given a value.

    To correct that, either add an Else clause with no conditions to give it a default value, or (shorter) set a default value in the declaration.


    The ColumnName variable has exactly the same issue.
    I was working through the code and I saw what you mean. I put the code within the IF block and I got no complaints. I am going to test to see if it works the way it's supposed to. Thanks si.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width