【发布时间】:2016-07-20 03:25:46
【问题描述】:
我正在尝试从 datagridview 中删除选定的行并在我的访问数据库中永久提交更改这是我的代码:
cn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Application.StartupPath & "\Accountcode.accdb;"
cn.Open()
Try
For Each row As DataGridViewRow In DataGridView1.SelectedRows
Using cn As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Application.StartupPath & "\Accountcode.accdb;")
Using cm As New OleDb.OleDbCommand
cm.Connection = cn
cm.CommandText = "DELETE * FROM CheckDJ WHERE [ID]= @id"
cm.CommandType = CommandType.Text
cm.Parameters.AddWithValue("@ID", CType(row.DataBoundItem, DataRowView).Row("ID"))
cm.ExecuteNonQuery()
End Using
End Using
Next
Catch ex As Exception
MsgBox(ex.Message)
End Try
Try
Using cn As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Application.StartupPath & "\Accountcode.accdb;")
Using cm As New OleDb.OleDbCommand
strsql = "SELECT * FROM CheckDJ"
cm.Connection = cn
cm.CommandText = strsql
cm.CommandType = CommandType.Text
Dim da As New OleDbDataAdapter(strsql, cn)
Dim ds As New DataSet()
da.Fill(ds, "CheckDJ")
DataGridView1.DataSource = ds.Tables(0)
End Using
End Using
Catch ex As Exception
MsgBox(ex.Message)
End Try
但我有一个错误。
指数超出范围。必须是非负数且小于集合的大小。
参数名称:索引
很感谢任何形式的帮助。提前谢谢!
【问题讨论】:
-
这是因为您在迭代行时删除了行。首先将它们放入一个集合中,然后循环遍历每个并将其从 datagridview 中删除,然后将其从数据库中删除。目前,您正在循环中从 datagridview 中删除记录,但您需要数据库并在此循环内再次填充 datagridview,这是不好的做法并提出问题......还使用参数并查看正确处理连接对象、命令等。 ..打开连接做你的工作,关闭和清理。
-
@Zaggler 如果您能通过向我展示正确的代码来帮助我,我将不胜感激。你可以修改我的代码。
-
@F0r3v3r-A-N00b 见上面我编辑的代码
标签: vb.net ms-access datagridview