Sunday, November 20, 2016

Post #8 : Programming " CRUD Part 2 - How to Select and Find data in SQL Server using VB.net"

Hi. Jack

now we will try to call the data that we have made in this post.

the scenario is, when we are typing the code in the code field and press enter the program will find the data in the database and display it if the code already exist in the database, if the code is not exist program will display "not found" message.



Click here to know what data is already made. or look sample below.




in the form that we have created this script .

  Private Sub Find()
        'filter if code is empty abort mission
        If Not tcode.Text = String.Empty Then
            'call connection string
            Using iKon = New SqlConnection(server_connection.connection_string)
                If iKon.State = ConnectionState.Open Then iKon.Close()
                iKon.Open()
                Try
                    'in this line you'll create command to insert the date into database using parameter @
                    Using iCmd = New SqlCommand("select * from cars where code = @code", iKon)
                        'declare sqlparameter and fillit with object (textbox,combobox, or data collection like list(of t)
                        iCmd.Parameters.Add(New SqlParameter("@code", tcode.Text))
                        'read data from database using reader
                        Using reader As SqlDataReader = iCmd.ExecuteReader
                            ' if reader has row, result not empty
                            If reader.HasRows = True Then
                                'read reader
                                While reader.Read
                                    'fill the textbox object
                                    tmerek.Text = reader("car_merk")
                                    ttype.Text = reader("car_type")
                                    tyear.Text = reader("car_year")
                                End While
                            Else
                                'if there is no return value or reader is nothing
                                MsgBox("Sorry, Code not found", MsgBoxStyle.Critical)
                            End If
                        End Using
                    End Using
                Catch ex As Exception
                    MsgBox("Error " & ex.Message, MsgBoxStyle.Critical)
                End Try
            End Using
        End If
    End Sub



 Private Sub tcode_KeyDown(sender As Object, e As KeyEventArgs) Handles tcode.KeyDown
        If e.KeyCode = 13 Then
            'call find method when button [ENTER]  pressed
            Find()
        End If
    End Sub



and run it.
if code found




if code not found


CONGRATULATIONS !!!

CRUD Part 1 - How to Insert or Create data in SQL Server using VB.net

Sample Project : Download Here

No comments:

Post a Comment