首页 > 解决方案 > 在 VB.NET (Visual Studio 2013) 中使用 OLEDB 通过 DataGridView 更新访问数据库的按钮

问题描述

我已将 Access 数据库链接到我的程序。它按预期填充 DataGridView,以便程序的一部分工作。但是,我添加到 DataGridView 的新数据不会显示,我不知道我的代码有什么问题。

任何人都可以看到任何错误或我错过的东西会导致代码无法按预期运行吗?先感谢您 :)

Imports System.Data.OleDb
Public Class Form1
    Dim j As OleDbConnection
    Dim a As OleDbDataAdapter
    Dim s As DataSet
    Dim lokasidb As String
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Call jaringan()
        a = New OleDbDataAdapter("Select * From datadairy", j)
        s = New DataSet
        s.Clear()
        a.Fill(s, "datadairy")
        DataGridDairy.DataSource = (s.Tables("datadairy"))
    End Sub

    Private Sub eksekusiSql(ByVal Sql As String)
        Dim objcmd As New System.Data.OleDb.OleDbCommand
        Call jaringan()
        Try
            objcmd.Connection = j
            objcmd.CommandType = CommandType.Text
            objcmd.CommandText = Sql
            objcmd.ExecuteNonQuery()
            objcmd.Dispose()
            MsgBox("The new data successfully saved", vbInformation)
        Catch ex As Exception
            MsgBox("The new data is failed to save", vbInformation)
        End Try
    End Sub

    Sub jaringan()
        lokasidb = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\19106060045_Tugas Modul 5.accdb"
        j = New OleDbConnection(lokasidb)
        If j.State = ConnectionState.Closed Then j.Open()
    End Sub

    Private Sub ButtonAdd_Click(sender As Object, e As EventArgs) Handles ButtonAdd.Click
        Dim No As String = TextNo.Text
        Dim Jenis_Susu_Sapi As String = TextSusu.Text
        Dim Jenis_Olahan As String = TextOlahan.Text
        Dim Harga_per_kg As String = TextHarga.Text
        Dim Tempat_Penjualan As String = TextPasar.Text
        Dim Sql_Simpan_Dairy As String = "Insert into datadairy (No, Jenis_Susu_Sapi, Jenis_Olahan, Harga_per_kg, Tempat_Penjualan) values (" + No + ",'" + Jenis_Susu_Sapi + "','" + Jenis_Olahan + "','" + Harga_per_kg + "','" + Tempat_Penjualan + "')"

        eksekusiSql(Sql_Simpan_Dairy)
        ShowDairydata()
    End Sub

    Public Sub ShowDairydata()
        Call jaringan()
        a = New OleDbDataAdapter("Select * from datadairy", j)
        s = New DataSet
        s.Clear()
        a.Fill(s, "datadairy")
        DataGridDairy.DataSource = (s.Tables("datadairy"))
    End Sub

标签: vb.netms-accessoledb

解决方案


将新数据添加到数据库后,只需使用

'DataGridDairy.Databind()'

刷新。


推荐阅读