数据库更改时vb.net自动更新datagridview

时间:2015-06-19 08:58:26

标签: database vb.net sql-server-2005 datagridview

我有一个应用程序,其中多个用户可以连接到数据库,并且当数据库中发生更改时,需要自动更新datagridview。可能没有计时器?

1 个答案:

答案 0 :(得分:0)

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