0

In the below code i want to validate and pop up a messagebox("NO RECORDS FOUND") when the given Input is not in the database? I dont know how to do it!

Note: Am using excel sheet as my Database.

Private Sub BtnSearch_Click(sender As Object, e As EventArgs) Handles BtnSearch.Click

        If TxtId.Text = "" Then
            MsgBox("Please enter a ID to search")
            Exit Sub
        End If

        Try
            FillDataGridView1("select * from [Sheet1$] where ID='" & TxtId.Text & "'")
            TxtFamilyname.Text = dt.Rows(0).Item(1)
            TxtGivenname.Text = dt.Rows(0).Item(2)
            TxtGender.Text = dt.Rows(0).Item(3)
            TxtDob.Text = dt.Rows(0).Item(4)
            TxtStreet.Text = dt.Rows(0).Item(5)
            TxtHouse.Text = dt.Rows(0).Item(6)
            TxtPostcode.Text = dt.Rows(0).Item(7)
            TxtCity.Text = dt.Rows(0).Item(8)
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, Text)
        End Try

End Sub
shaik izaz
  • 81
  • 1
  • 1
  • 7

1 Answers1

0

The construct you're looking for is called an If statement. Something like this:

FillDataGridView1("select * from [Sheet1$] where ID='" & TxtId.Text & "'")
If dt.Rows.Count < 1 Then
    MsgBox("No record found");
    Exit Sub
End If
' the rest of your code

It's not entirely clear what FillDataGridView1 does internally, presumably it both queries the data and updates the UI. I'd recommend separating those two concerns into distinct pieces of functionality, because updating the UI when there's no data to display could result in a strange user experience.

If you query the data first, then you can examine the results of the query before updating the UI. That way you can more cleanly express the fact that there are no records to show.


Also, it's worth noting that your code is highly vulnerable to SQL injection attacks. You should really look into using parameterized queries.

Community
  • 1
  • 1
David
  • 208,112
  • 36
  • 198
  • 279