How to modify my RunQuery to show a message if the result shows no records

Claude Larocque 666 Reputation points
2022-01-16T16:25:11.697+00:00

Hi everyone,
I have a classe named SQLControl and a sub named RunQuery, how can I modify that sub to show this message if the result returns no record:

"There is no record for this query, please try again" I am receiving the message "There is no row in position 0." and it should be easy to change that message no?

I show you all the class.

Imports System.Data.SqlClient  
Public Class SQLControl  
    Public UsernameFriend As String  
    Public ConnectionString As String = ""  
    Public ConnectionObj As System.Data.SqlClient.SqlConnection = Nothing  
    Public TransactionObj As System.Data.SqlClient.SqlTransaction = Nothing  
  
    Public DBCon As New SqlConnection("Data Source=ACSERVER\ACRSERVER;Initial Catalog=ACData;Integrated Security=SSPI;")  
  
    Public DBCmd As SqlCommand  
  
    'DB DATA  
    Public DBDA As SqlDataAdapter  
    Public DBDT As DataTable  
    Public DBDS As DataSet  
    Public DBDR As SqlDataReader  
  
    'QUERY PARAMETERS  
    Public Params As New List(Of SqlParameter)  
  
    'QUERY STATISTICS  
    Public RecordCount As Integer  
    Public Exception As String  
  
    Public Sub New()  
    End Sub  
  
    'ALLOW CONNECTION STRING OVERRIDE  
    Public Sub New(ConnectionString As String)  
        DBCon = New SqlConnection(ConnectionString)  
    End Sub  
  
    Public Function CloseDatabase(ByRef ErrorMSG As String) As Boolean  
        Try  
            Me.Rollback()  
            TransactionObj.Dispose()  
            ConnectionObj.Close()  
            ConnectionObj.Dispose()  
            Return True  
        Catch ex As Exception  
            ErrorMSG = ex.Message  
  
            Return False  
        End Try  
    End Function  
    Public Sub Rollback()  
        TransactionObj.Rollback()  
        TransactionObj.Dispose()  
        TransactionObj = ConnectionObj.BeginTransaction  
    End Sub  
  
    Public Function HasConnection() As Boolean  
        Try  
            DBCon.Open()  
  
            DBCon.Close()  
            Return True  
        Catch ex As Exception  
            MsgBox(ex.Message)  
  
        End Try  
  
        Return False  
  
    End Function  
  
    Public Sub RunQuery(Query As String)  
        Try  
            DBCon.Open()  
  
            'CREATE COMMAND  
            DBCmd = New SqlCommand(Query, DBCon)  
  
            'FILL DATASET  
            DBDA = New SqlDataAdapter(DBCmd)  
            DBDS = New DataSet  
            DBDA.Fill(DBDS)  
  
            DBCon.Close()  
  
        Catch ex As Exception  
            MsgBox(ex.Message)  
  
  
            'MAKE SURE CONNECTION IS CLOSE  
            If DBCon.State = ConnectionState.Open Then  
                DBCon.Close()  
            End If  
        End Try  
    End Sub  
  
    Public Sub GetSQLQueries(Query As String)  
        Try  
            DBCon.Open()  
            DBCmd = New SqlCommand(Query, DBCon)  
  
            ' LOAD SQL RECORDS IN A DATAGRID  
            DBDA = New SqlDataAdapter(DBCmd)  
            DBDS = New DataSet  
            DBDA.Fill(DBDS)  
            DBCon.Close()  
  
        Catch ex As Exception  
            MsgBox(ex.Message)  
  
  
            'MAKE SURE CONNECTION IS CLOSE  
            If DBCon.State = ConnectionState.Open Then  
                DBCon.Close()  
            End If  
        End Try  
    End Sub  
  
    'EXECUTE QUERY SUB  
    Public Sub ExecQuery(Query As String, Optional ReturnIdentity As Boolean = False)  
        ' RESET QUERY STATS  
        RecordCount = 0  
        Exception = ""  
  
        Try  
            DBCon.Open()  
  
            'CREATE DB COMMAND  
            DBCmd = New SqlCommand(Query, DBCon)  
  
            'LOAD PARAMS INTO DB COMMAND  
            Params.ForEach(Sub(p) DBCmd.Parameters.Add(p))  
  
            ' CLEAR PARAMS LIST  
            Params.Clear()  
  
            ' EXECUTE COMMAND & FILL DATASET  
            DBDT = New DataTable  
            DBDA = New SqlDataAdapter(DBCmd)  
            DBDS = New DataSet  
            RecordCount = DBDA.Fill(DBDT)  
            If ReturnIdentity = True Then  
                Dim ReturnQuery As String = "SELECT @@IDENTITY As LastID;"  
                '@@IDENTITY  
                'SCOPE_IDENTITY() SESSION & SCOPE - To analyse  
                'IDENT_CURRENT(tablename) to get the last ID in your database, any scope, any session  
                DBCmd = New SqlCommand(ReturnQuery, DBCon)  
                DBDT = New DataTable  
                DBDA = New SqlDataAdapter(DBCmd)  
                RecordCount = DBDA.Fill(DBDT)  
            End If  
        Catch ex As Exception  
            'CAPTURE ERROR  
            Exception = "ExecQuery Error: " & vbNewLine & ex.Message  
  
        Finally  
            ' CLOSE CONNECTION  
            If DBCon.State = ConnectionState.Open Then DBCon.Close()  
        End Try  
    End Sub  
  
    'ADD PARAMS  
    Public Sub AddParam(Name As String, Value As Object)  
        Dim NewParam As New SqlParameter(Name, Value)  
        Params.Add(NewParam)  
    End Sub  
  
    'ERROR CHECKING  
    Public Function HasException(Optional Report As Boolean = False) As Boolean  
        If String.IsNullOrEmpty(Exception) Then Return False  
        If Report = True Then MsgBox(Exception, MsgBoxStyle.Critical, "Exception:")  
        Return True  
    End Function  
    Public Function IsFormOpen(ByVal frm As Form) As Boolean  
        If Application.OpenForms.OfType(Of Form).Contains(frm) Then  
            Return True  
        Else  
            Return False  
        End If  
    End Function  
    Public Function FillDataTable(SQL As String, ParamArray PRM() As Object) As DataTable  
        Dim CMD As New SqlClient.SqlCommand With {  
        .Connection = ConnectionObj,  
        .Transaction = TransactionObj,  
        .CommandText = SQL}  
        Dim I As Integer  
        For I = 0 To PRM.Count - 1  
            CMD.Parameters.AddWithValue("@" & I.ToString, PRM(I))  
        Next  
        Dim DBDA As New SqlClient.SqlDataAdapter  
        Dim DBDT As New DataTable  
        DBDA.SelectCommand = DBCmd  
        DBDA.Fill(DBDT)  
        CMD.Dispose()  
        DBDA.Dispose()  
        Return DBDT  
    End Function  
  
    Public Sub Commit()  
        TransactionObj.Commit()  
        TransactionObj.Dispose()  
        TransactionObj = ConnectionObj.BeginTransaction  
    End Sub  
  
    Public Sub ExecuteSQL(SQL As String, ParamArray PRM() As Object)  
        Dim CMD As New SqlClient.SqlCommand With {  
        .Connection = ConnectionObj,  
        .Transaction = TransactionObj,  
        .CommandText = SQL}  
        Dim I As Integer  
        For I = 0 To PRM.Count - 1  
            CMD.Parameters.AddWithValue("@" & I.ToString, PRM(I))  
        Next  
        CMD.ExecuteNonQuery()  
    End Sub  
  
End Class  

Thank you
Claude from Quebec, Canada

Azure NetApp Files
Azure NetApp Files
An Azure service that provides enterprise-grade file shares powered by NetApp.
93 questions
SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
13,977 questions
{count} votes

Accepted answer
  1. Viorel 118K Reputation points
    2022-01-16T17:29:48.193+00:00

    If the standard message is displayed by MsgBox(ex.Message) in BtnOK_Click, then try adding an If after RunQuery:

    . . .
    SQL.RunQuery("SELECT . . . ")
    If SQL.DBDS.Tables(0).Rows.Count = 0 Then
        MsgBox( "There is no record for this query, please try again." )
        Exit Sub
    End If
    . . .
    

2 additional answers

Sort by: Most helpful
  1. Claude Larocque 666 Reputation points
    2022-01-16T17:19:17.627+00:00

    Thanks for the quick response, here is a screen shot and the necessary code:

    165414-there-is-no-row.jpg

        Private Sub BtnOK_Click(sender As Object, e As EventArgs) Handles BtnOK.Click  
            Try  
                If String.IsNullOrEmpty(GiftCertificateNumberTB.Text.Trim()) Then  
                    MessageBox.Show("A gift certificate number is mandatory, enter or scan the certificate number!.",  
                                    "Auto Cash Register Message", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)  
                    Exit Sub  
                End If  
                'CLEAR EXISTING RECORD  
                If SQL.DBDS IsNot Nothing Then  
                    SQL.DBDS.Clear()  
                End If  
                SQL.RunQuery("SELECT * FROM Application.GiftCertificates Where CertificateNumber = '" & GiftCertificateNumberTB.Text & "' ")  
                If SQL.DBDS.Tables(0).Rows(0).Item(0) <> 0 Then  
                    Dim FormValidateGiftCertificate As New FrmValidateGiftCertificate  
                    FrmValidateGiftCertificate.ShowDialog()  
                Else  
                    Exit Sub  
                End If  
      
                If SQL.HasException(True) Then Exit Sub  
            Catch ex As Exception  
                MsgBox(ex.Message)  
                System.IO.File.AppendAllText("C:\AutoCashRegister\Documents\log.txt", ex.ToString & vbNewLine & vbNewLine)  
            End Try  
        End Sub  
    
    0 comments No comments

  2. Claude Larocque 666 Reputation points
    2022-01-16T17:20:23.247+00:00

    The gift certificate 1 exist but not the 2 :)

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.