我能够成功将Excel“数据库”添加到我的程序中。但是,我对搜索功能和保存功能的工作方式有点困惑。我想这样做,以便用户可以直接在DataGridView中编辑文本并保存他们的工作(这将保存到本地excel文件)。我正在学习一个教程,但是我的程序根据他们的工作不起作用,特别是搜索和保存按钮。每次我输入并点击“搜索”,我总是会收到错误
标准表达式中的数据类型不匹配。
链接到教程我是下面的: Save, Search, Edit Excel from VB.NET
基本上,我想做到这一点,以便用户可以通过VB.NET控制excel表单。我知道这似乎有点无用(因为用户无论如何都可以打开excel文件......)但我现在只是在试验(相对较新的VB.NET)。
我的代码:
Imports System.Data.OleDb
Public Class Form1
Dim cn As New OleDbConnection
Dim cm As New OleDbCommand
Dim da As OleDbDataAdapter
Dim dt As New DataTable
Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs)
cn.Close()
End Sub
Private Sub FillDataGridView(ByVal Query As String)
da = New OleDbDataAdapter(Query, cn)
dt.Clear()
da.Fill(dt)
With DataGridView1
.DataSource = dt
.Columns(0).HeaderText = "Id"
.Columns(1).HeaderText = "Nama Agen"
.Columns(1).AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
End With
End Sub
Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
Try
FillDataGridView("select * from [Data Agen$] where id='" & txtID.Text.ToString() & "'")
txtName.Text = dt.Rows(0).Item(1)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Try
With cm
.Connection = cn
.CommandText = "insert into [Data Agen$]values('" & txtID.Text & "','" & txtName.Text & "')"
.ExecuteNonQuery()
End With
FillDataGridView("select * from [Data Agen$]")
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical, Text)
Return
End Try
MsgBox("Successfully updated!", MsgBoxStyle.Information, Text)
End Sub
Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
Try
With cm
.Connection = cn
.CommandText = "Update [Data Agen$] set [nama agen] = '" & txtName.Text & "' where id='" & txtID.Text & "'"
.ExecuteNonQuery()
End With
FillDataGridView("select * from [Data Agen$]")
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical, Text)
Return
End Try
MsgBox("Successfully updated!", MsgBoxStyle.Information, Text)
End Sub
Private Sub btnRefresh_Click(sender As Object, e As EventArgs) Handles btnRefresh.Click
FillDataGridView("select * from [Data Agen$]")
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
cn.ConnectionString = "provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\Users\FEQH\Documents\Visual Studio 2012\Projects\exceltester\test.xls;Extended Properties=Excel 8.0;"
cn.Open()
FillDataGridView("select * from [Data Agen$]")
Button1.Visible = False
End Sub
End Class