Write a VB.NET program to create a table student (Roll No, SName, Class, City). Insert the records (Max: 5). Update the city of students to ‘Pune’ whose city is ‘Mumbai’ and display updated records in a GridView. 

Answer:

Imports System.Data
Imports System.Data.OleDb

Public Class Form1
    Dim con As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\path_to_your_database\your_database.accdb")
    Dim cmd As New OleDbCommand
    Dim adpt As New OleDbDataAdapter("SELECT * FROM student", con)
    Dim ds As New DataSet

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

    Private Sub LoadData()
        adpt.Fill(ds, "student")
        DataGridView1.DataSource = ds
        DataGridView1.DataMember = "student"
    End Sub

    Private Sub btnInsert_Click(sender As Object, e As EventArgs) Handles btnInsert.Click
        cmd.Connection = con
        cmd.CommandType = CommandType.Text
        cmd.CommandText = "INSERT INTO student (RollNo, SName, Class, City) VALUES (" & 
                          TextBox1.Text & ",'" & TextBox2.Text & "','" & TextBox3.Text & "','" & TextBox4.Text & "')"
        
        con.Open()
        cmd.ExecuteNonQuery()
        con.Close()

        MessageBox.Show("Record inserted successfully.")
        ds.Clear()
        LoadData()
    End Sub

    Private Sub btnUpdateCity_Click(sender As Object, e As EventArgs) Handles btnUpdateCity.Click
        cmd.Connection = con
        cmd.CommandType = CommandType.Text
        cmd.CommandText = "UPDATE student SET City = 'Pune' WHERE City = 'Mumbai'"

        con.Open()
        Dim rowsAffected As Integer = cmd.ExecuteNonQuery()
        con.Close()

        If rowsAffected > 0 Then
            MessageBox.Show("City updated successfully.")
        Else
            MessageBox.Show("No records found with the city 'Mumbai'.")
        End If

        ds.Clear()
        LoadData()
    End Sub
End Class
Scroll to Top