0

I've trying to find a solution but haven't had success yet, My program will let the user get data from an Oracle database to a datagrid and let them export to Excel, but when trying to use a datetimepicker to use as a value in my query the debugger gets me a NullReferenceException error with a Object reference not set to an instance of an object error. Here is my code (I've cleared the connection data for security).

Imports System
Imports System.Collections.Generic
Imports System.Data
Imports Oracle.DataAccess.Client 'ODP.NET Oracle managed provider
Imports Oracle.DataAccess.Types
Imports System.IO
Imports System.Text.RegularExpressions
Imports System.Threading

Public Class frmReport2
 Dim rs As New Resizer
 Dim UpdateThread As Thread
 Dim UpdateThreadStart As New ThreadStart(AddressOf QueryDataBase)
 Dim CallDataBindToDataGrid As New MethodInvoker(AddressOf 
 Me.DataBindToDataGrid)
 Dim MyDataSet As DataSet
 Dim MyDataAdapter As OracleDataAdapter

Dim MyQueryString As String =
    "SELECT b.VEH_CODIGO_MAEXBIC AS AUTOBUS, a.STV_CAMARA AS CÁMARA, a.STV_FICHERO AS ARCHIVO," &
    "TO_CHAR(CAST(a.STV_INICIO AS DATE),'DD/MM/YYYY') AS FECHA_INICIO, TO_CHAR(CAST(a.STV_INICIO AS DATE),'HH24:MI:SS')" &
    "AS HORA_INICIO, TO_CHAR(CAST(a.STV_FIN AS DATE),'DD/MM/YYYY') AS FECHA_FIN, TO_CHAR(CAST(a.STV_FIN AS DATE),'HH24:MI:SS')" &
    "AS HORA_FIN FROM SAE_STATUS_VIDEO a INNER JOIN CVI_VEHICULOS b ON a.STV_STE_ID = b.VEH_ID" &
    "WHERE TO_CHAR(CAST(a.STV_INICIO AS DATE),'DD/MM/YYYY') BETWEEN '" + DateFchInicio.Value + "' AND '" + DateFchFin.Value + "' " &
    "AND TO_CHAR(CAST(a.STV_INICIO As Date),'HH24:MI:SS') BETWEEN '" + DateHrInicio.Value + "' AND '" + DateHrFin.Value + "' ORDER BY STV_INICIO DESC;"

Dim MyConnection As New OracleConnection("")
Private Sub frmReport2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Control.CheckForIllegalCrossThreadCalls = False
    rs.FindAllControls(Me)
    TStripStLabel.Text = "Listo"

End Sub

Private Sub frmReport2_Resize(sender As Object, e As EventArgs) Handles Me.Resize
    rs.ResizeAllControls(Me)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles BtnBuscar.Click
    UpdateThread = New Thread(UpdateThreadStart)
    UpdateThread.IsBackground = True
    UpdateThread.Name = "Update Thread"
    UpdateThread.Start()


End Sub

' Sub routine that is to be executed on Form's thread.
Public Sub DataBindToDataGrid()
    DGVOra.DataSource = MyDataSet
    DGVOra.DataMember = "SAE_STATUS_VIDEO"
    'MyDataAdapter = Nothing
    'MyDataSet = Nothing
End Sub

' Sub routine used by the background thread to query database.
Public Sub QueryDataBase()
    MyDataSet = New DataSet()
    MyConnection.Open()
    Dim cmd As New OracleCommand(MyQueryString, MyConnection)
    MyDataAdapter = New OracleDataAdapter(cmd)
    'LblStatus.Text = "Buscando Información"
    TStripStLabel.Text = "Buscando Información"
    MyDataAdapter.Fill(MyDataSet, "SAE_STATUS_VIDEO")
    MyConnection.Close()
    'LblStatus.Text = "Operación finalizada"
    TStripStLabel.Text = "Operación Finalizada"
    ' Make asynchronous function call to Form's thread.
    Me.BeginInvoke(CallDataBindToDataGrid)
End Sub

Private Sub SalirToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SalirToolStripMenuItem.Click
    Dim result As DialogResult = MessageBox.Show("Estas seguro que deseas salir?", "Desea Salir?", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
    If result = DialogResult.Yes Then
        Application.Exit()
    End If
    'MsgBox("Estas seguro que deseas salir?", MsgBoxStyle.OkCancel, "Desea Salir?", Msg) = MsgBoxResult.Ok Then
 End Sub
End Class
rwffh
  • 11
  • 6
  • I can hardly see where you are using a DateTimePicker? – muffi Mar 22 '18 at 14:29
  • I'm using 4, two for date and two more for time only, they are DateFchInicio, DateFchFin, DateHrInicio, DateHrFin – rwffh Mar 22 '18 at 14:31
  • 1
    There's a duplicate question that explains how to investigate and solve such problems. It's impossible to help with *this* question though, since you don't even mention *where* that exception occurs. – Panagiotis Kanavos Mar 22 '18 at 14:34
  • There too many smells in this code that could lead to far worse problems. By concatenating strings to create SQL queries not only do you expose yourself to SQL Injection attacks, the query can fail because eg a number or date was converted to a string using an unexpected format. Even if the query runs, it may return no results and possibly lead to a NRE – Panagiotis Kanavos Mar 22 '18 at 14:36
  • If you're much more familiar with VB than C#, make sure to look beyond the top voted C# based answer on the duplicate, there's an equally in depth one [aimed at VB](https://stackoverflow.com/a/26761773/791010). – James Thorpe Mar 22 '18 at 14:37
  • @PanagiotisKanavos Sorry, the exception occurs on this line Dim MyQueryString As String – rwffh Mar 22 '18 at 14:37
  • References to *threads* and *grids* in the same line? I can't see where grids and threads are used in all this, but you *can't* modify the UI from a background thread. If you want to load data in the background, use `async/await` and eg ExecuteReaderAsync` or wrap the code that loads the data inside an `Await Task.Run` and update the grid *afterwards* – Panagiotis Kanavos Mar 22 '18 at 14:38
  • @rwffh possibly because there's no valid date selection. Another smell. You should *check* that there is a valid value before trying to use it. What if it was a textbox with the text `'; drop table users; --` ? – Panagiotis Kanavos Mar 22 '18 at 14:39
  • 2
    @rwffh or *maybe* because there's no datepicker at that point. You are initializing a *field*, something that happens right after a class's constructor completes but *before* any other method is called. Form components are created later – Panagiotis Kanavos Mar 22 '18 at 14:41
  • I think that's probably it. OP: It looks like you've created the field as a template for the SQL, but it's being parsed once at the wrong time rather than each time you need it - this is another reason to look at parameterised queries - that way you could have your query stored as a static field at that point, just passing in the parameters where necessary. – James Thorpe Mar 22 '18 at 14:44
  • You were right, I've moved the query string to another sub and it doesn't show the NRE anymore. Thanks!! – rwffh Mar 22 '18 at 15:52

1 Answers1

0

Moved the query string to a different sub

rwffh
  • 11
  • 6