I'm fairly new to .NET programming. I am trying to check if there are settings in a database table and if not, create some default settings. The problem is that when there are no settings I need to make two calls with the datareader and it keeps giving me problems.
I originally was only using one datareader but made two to attempt resolving my issue, didn't work.
Then I tried closing the datareader and I get errors because it returned a nullreference.
If I try to close it I get an issue, if I don't close it the next one gives me an error saying there is already an open datareader on this connection that needs to be closed. Can anyone tell me how I can refactor my code to get this to work (preferably with one datareader)?
I also tried putting the reader.close() in another set of try catch, while that enables me to catch the error, it still doesn't close the datareader so I am at a loss.
Private Sub Get_Initial_Settings()
Dim reader1 As MySqlDataReader = Nothing, reader2 As MySqlDataReader = Nothing
Dim cmd As New MySqlCommand("SELECT depot, size, roc_family, wil_family, ast_family, met_family, ric_family, view FROM vb_dashboard.user_preferences WHERE " & GetUserName() & "", conn)
Dim hasSettings As Boolean
'Get Personal Settings or initiate them if necessary
Try
reader1 = cmd.ExecuteReader
hasSettings = True
MessageBox.Show("Your user settings show you have a selected depot of " & reader1(0).ToString)
Catch ex As Exception
'No settings exist, set some up
MessageBox.Show("You have no settings for this program yet")
hasSettings = False
Finally
reader1.Close()
End Try
'User has no preferences, Create some
'First, create a list of depots to select from and add it to a combobox
If (hasSettings = False) Then
Try
cmd.CommandText = "SELECT depot FROM vb_dashboard.depots ORDER BY depot"
reader2 = cmd.ExecuteReader
While (reader2.Read)
dlgSelectDepot.cbDepotSelect.Items.Add(reader2.GetString(0))
End While
'Now show the dialog box to initiate a depot setting
Me.Hide()
dlgSelectDepot.Show()
Me.Show()
If (dlgSelectDepot.DialogResult = Windows.Forms.DialogResult.Cancel) Then
Me.Close()
End If
cmd.CommandText = "INSERT INTO vb_database.user_preferences SET user='" & GetUserName.ToUpper & "', depot='Rochester'"
cmd.ExecuteNonQuery()
Catch ex As Exception
MessageBox.Show("An error has occurred: " & ex.Message)
Finally
reader2.Close()
End Try
End If
End Sub