vb.net auto update datagridview when database change

1.3k Views Asked by At

I have an application where multiple users can connect to a database and datagridview need to be updated automatically when there has been a change in the database. Possible without timers?

1

There are 1 best solutions below

0
On
Public Class Form1
    Dim dbDataAdapter As OleDb.OleDbDataAdapter = New OleDb.OleDbDataAdapter
    Dim dbDataSet As DataSet = New DataSet

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim con As OleDb.OleDbConnection = New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\database1.accdb;Persist Security Info=False;")  ' Use relative path to database file
        Dim cmd As OleDb.OleDbCommand = New OleDb.OleDbCommand("SELECT * FROM Table1", con)

        con.Open()

        'Dim dbDataAdapter As OleDb.OleDbDataAdapter = New OleDb.OleDbDataAdapter
        dbDataAdapter = New OleDb.OleDbDataAdapter(cmd)

        'Here one CommandBuilder object is required.
        'It will automatically generate DeleteCommand,UpdateCommand and InsertCommand for DataAdapter object  
        Dim builder As OleDb.OleDbCommandBuilder = New OleDb.OleDbCommandBuilder(dbDataAdapter)

        'Dim dbDataSet As DataSet = New DataSet
        dbDataAdapter.Fill(dbDataSet, "MyTable")
        DataGridView1.DataSource = dbDataSet.Tables("MyTable").DefaultView

        con.Close()
        con = Nothing
    End Sub

    Private Sub DataGridView1_CellValueChanged(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellValueChanged
        Me.Validate()
        Me.dbDataAdapter.Update(Me.dbdataset.Tables("MyTable"))
        Me.dbDataSet.AcceptChanges()
    End Sub
End Class