想要使用Access数据库列

时间:2015-07-21 10:48:41

标签: vb.net datagridview

我正在使用VB2010和Access2007

我希望能够在Access数据库中添加/删除列,并在运行时使用代码在DataGridView中显示结果。

我的VB表单有一个AddColumn按钮要添加,DropColumn按钮用于从数据库中删除列,而GataGridView1用于显示结果。

AddColumn将列添加到数据库和DataGridView。 DropColumn从数据库中删除列,但不从DataGridView中删除列。 这是我的问题,如何从DataGridView1以及数据库中删除列!

我徒劳地试图找到解决这个问题的方法,并欢迎您提出任何建议。

这是我的VB代码

Imports System.Data.OleDb。

Public Class Form3

Dim con1 As New OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source = I:/AccessDGV/dbAccessDGV.mdb")
Dim da As New OleDbDataAdapter("SELECT * FROM tblContacts", con1)

Dim dt As New DataTable
Dim bs As New BindingSource

Private Sub Form3_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load

    Dim conString As String = My.Settings.dbAccessDGVConnectionString
    Dim con1 As New OleDbConnection(conString)
    Dim CB As New OleDbCommandBuilder(da)
    da.Fill(dt)
    bs.DataSource = dt

    DataGridView1.DataSource = bs

End Sub

Private Sub btnAddColumn_Click(sender As System.Object, e As System.EventArgs) Handles btnAddColumn.Click

    con1.Open()
    Dim sqladdcolumn As String = "ALTER TABLE tblContacts ADD COLUMN Extra1 Text"
    Dim cmd As OleDbCommand = New OleDbCommand(sqladdcolumn, con1)

    Try
        cmd.ExecuteNonQuery()
        da.Fill(dt)
        cmd.Dispose()
        con1.Close()
    Catch ex As Exception
        MsgBox(ex.Message)
        con1.Close()
    End Try

End Sub

Private Sub btnDropColumn_Click(sender As System.Object, e As System.EventArgs) Handles btnDropColumn.Click

    con1.Open()
    Dim sqldropcolumn As String = "ALTER TABLE tblContacts DROP COLUMN Extra1 Text"
    Dim cmd As OleDbCommand = New OleDbCommand(sqldropcolumn, con1)

    Try
        cmd.ExecuteNonQuery()
        da.Fill(dt)
        cmd.Dispose()
        con1.Close()
    Catch ex As Exception
        MsgBox(ex.Message)
        con1.Close()
    End Try

End Sub

结束班

1 个答案:

答案 0 :(得分:0)

您需要将数据源重新绑定到gridview。发生的事情是gridview仍然绑定到仍然有列的“旧”数据源。

Private Sub btnDropColumn_Click(sender As System.Object, e As System.EventArgs) Handles btnDropColumn.Click

con1.Open()
Dim sqldropcolumn As String = "ALTER TABLE tblContacts DROP COLUMN [Extra1 Text]"
Dim cmd As OleDbCommand = New OleDbCommand(sqldropcolumn, con1)

Try
    cmd.ExecuteNonQuery()
    'clear the datatable.
    dt.clear()
    da.Fill(dt)
    cmd.Dispose()
    con1.Close() 
    ' Rebind the datasource of the gridview.        
    DataGridView1.DataSource = dt
    DataGridView1.Refresh()
Catch ex As Exception
    MsgBox(ex.Message)
    con1.Close()
End Try

End Sub

更新更改了查询字符串。 我认为问题可能在于查询字符串。它试图删除的列名是Extra1而不是Extra1 Text。