Add columns to Microsoft Access Table - Visual Basic .NET

Tags: VB.NET, VB 2008, VB 2010, VB 2012, VB 2013

This tutorial describes how to add columns to Microsoft Access table in runtime in Visual Basic .NET

Add the followind code before the (Public Class Form1) line:

Imports System.Data.OleDb

Then add the following declarations below the (Public Class Form1) line

    Dim provider As String
    Dim dataFile As String
    Dim connString As String
    Dim myConnection As OleDbConnection = New OleDbConnection

The following is the Add Columns button click event code:

 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
        dataFile = "C:\Users\Jimmy\Desktop\test.accdb"
        connString = provider & dataFile
        myConnection.ConnectionString = connString
        myConnection.Open()
        Dim str As String = "ALTER TABLE Items ADD COLUMN LName TEXT"
        'Items is the table name 
        'LName is the new column name
        'TEXT is the new column Type.
        Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
        Try
            cmd.ExecuteNonQuery()
            cmd.Dispose()
            myConnection.Close()
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub


Share This

Home | About | Contact | Privacy Policy

Copyright visual-basic-tutorials.com 2017 - All Rights Reserved.