Write a VB.NET program to create a movie table (Mv_Name, Release_year, Director). Insert the records (Max: 5). Delete the records of movies whose release year is 2022 and display an appropriate message in a message box.

Answer:

Imports System
Imports System.Data
Imports System.Data.OleDb

Public Class Form1

    Dim con As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Saurabh\Desktop\New folder\movie.accdb")
    Dim adpt As New OleDbDataAdapter("Select * from movie", con)
    Dim cmd As New OleDbCommand
    Dim ds As New DataSet

    Public Function display()
        adpt.Fill(ds, "movie")
        DataGridView1.DataSource = ds
        DataGridView1.DataMember = "movie"
        Return ds
    End Function

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        display()
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        If String.IsNullOrEmpty(TextBox1.Text) Or String.IsNullOrEmpty(TextBox2.Text) Or String.IsNullOrEmpty(TextBox3.Text) Then
            MessageBox.Show("Please fill all fields.")
            Exit Sub
        End If

        Try
            cmd.Connection = con
            cmd.CommandType = CommandType.Text
            cmd.CommandText = "INSERT INTO movie (Mv_Name, Release_year, Director) VALUES ('" & TextBox1.Text & "', " & TextBox2.Text & ", '" & TextBox3.Text & "')"
            
            con.Open()
            
            If cmd.ExecuteNonQuery() > 0 Then
                MessageBox.Show("Inserted Successfully...!")
            Else
                MessageBox.Show("Failed to insert.")
            End If
        Catch ex As Exception
            MessageBox.Show("Error: " & ex.Message)
        Finally
            con.Close()
            ds.Clear()
            display()
        End Try
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        If Not String.IsNullOrEmpty(TextBox2.Text) Then
            MessageBox.Show("Do not enter a year in the second text box for deletion.")
            Exit Sub
        End If

        Try
            cmd.Connection = con
            cmd.CommandType = CommandType.Text
            cmd.CommandText = "DELETE FROM movie WHERE Release_year = 2022"

            con.Open()

            Dim rowsAffected As Integer = cmd.ExecuteNonQuery()
            
            If rowsAffected > 0 Then
                MessageBox.Show("Deleted successfully...!")
            Else
                MessageBox.Show("No records found for 2022.")
            End If
        Catch ex As Exception
            MessageBox.Show("Error: " & ex.Message)
        Finally
            con.Close()
            ds.Clear()
            display()
        End Try
    End Sub
End Class
Scroll to Top