我有一个使用OleDB打开Excel工作表并将其显示在datagridview中的应用程序。目前,我可以打开工作表-但保存时遇到了问题。
这是我的声明:
Dim sFileName As String = "FILEPATH AND SHEET.xls"
Dim iCommand As OleDbCommand
Dim iAdapter As OleDbDataAdapter
Dim iBuilder As OleDbCommandBuilder
Dim iDs As DataSet
Dim iTable As DataTable
Dim iConnString As String = "provider=Microsoft.Jet.OLEDB.4.0;Data Source='" & sFileName & "';Extended Properties=Excel 8.0;"
Dim iConnSelect As String = "SELECT * FROM [Sheet1$]"
Dim iConn As New OleDbConnection(iConnString)
这是我的表单加载(我正在尝试在此处打开工作表并使用数据绑定轻松保存):
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
DataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells
DataGridView1.Columns(4).DefaultCellStyle.WrapMode = DataGridViewTriState.[True]
With DataGridView1
.Rows.Clear()
.Columns.Clear()
End With
iConn.Open()
iCommand = New OleDbCommand(iConnSelect, iConn)
iAdapter = New OleDbDataAdapter(iCommand)
iBuilder = New OleDbCommandBuilder(iAdapter)
iDs = New DataSet()
iAdapter.Fill(iDs, "Incoming")
iTable = iDs.Tables("Incoming")
iConn.Close()
DataGridView1.DataSource = iDs.Tables("Incoming")
'ColumnName is a unique column with an ID
iTable.PrimaryKey = New DataColumn() {iTable.Columns("ColumnName")}
' ADD A BUTTON AT THE LAST COLUMN IN EVERY ROW.
Dim btn1 = New DataGridViewButtonColumn()
btn1.HeaderText = ""
btn1.Text = "Complete"
btn1.Name = "btnComplete"
btn1.UseColumnTextForButtonValue = True
DataGridView1.Columns.Add(btn1)
End Sub
最后...我的保存按钮:
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
iAdapter.Update(iTable)
End Sub
所以,我希望这可以保存,但出现此错误:
System.Data.dll中发生了类型为'System.InvalidOperationException'的未处理异常
其他信息:不返回任何键列信息的SelectCommand不支持为UpdateCommand动态生成SQL。
有人可以帮忙吗?我不知道怎么了。我已经尝试设置主键,但是仍然出现此错误。
答案 0 :(得分:0)
我非常确定这些异常意味着您的选择查询需要返回表的主键。如果您的表没有主键,则需要设置一个。