"No value given for one or more required parameters" VB.Net 网格视图更新

"No value given for one or more required parameters" VB.Net GridView Update

我有一个 Access 数据库并通过 VB.NET 连接到它。

首先,我在 GridView 中显示 table 条记录,用户可以更新它。用户更新后,他会按一个ButtonGridView中取出更新的数据并更新Access数据库。

但是在这样做时我得到了错误 No value given for one or more required parameters. 我在这里遗漏了什么?

代码:

 Dim sConnectionString As String _
       = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\DB.accdb;Persist Security Info=False;"

Dim myConnection As OleDbConnection
Dim myAdapter As OleDbDataAdapter
Dim myTable As DataTable

Private Sub form1_Shown(sender As Object, e As EventArgs) Handles MyBase.Shown
        myConnection = New OleDbConnection(sConnectionString)
        Dim myCommand As New OleDbCommand("SELECT ID,Test FROM T1", myConnection)
        myConnection.Open()
        myAdapter = New OleDbDataAdapter(myCommand)
        myTable = New DataTable()
        myAdapter.Fill(myTable)
        setDataGridDataSource(myTable)
        setLabelTxt("Row Count: " + myTable.Rows.Count.ToString(), RowCount)
        DataGridView1.AllowUserToAddRows = True
        DataGridView1.AllowUserToDeleteRows = True
        DataGridView1.EditMode = DataGridViewEditMode.EditOnEnter
        myConnection.Close()
    End Sub

Private Sub button1_Click(sender As Object, e As EventArgs) Handles button1.Click
    Me.Validate()
    Dim command As OleDbCommand = New OleDbCommand("UPDATE T1 SET ID = ? , Test = ? WHERE ID = ?;", myConnection)
    myAdapter.UpdateCommand = command
    myAdapter.Update(myTable)
    myTable.AcceptChanges()
End Sub

带有文本 "UPDATE T1 SET ID = ? , Test = ? WHERE ID = ?;" 的 sql 命令需要 3 个参数,但您没有在代码中的任何位置设置它们。 See this example 并将参数分配给您的命令,如:

cmd.Parameters.AddWithValue("ID", txtID.Text);
cmd.Parameters.AddWithValue("Test", txtTest.Text);
... and so on

代码应编辑为:

Private Sub button1_Click(sender As Object, e As EventArgs) Handles button1.Click
        Me.Validate()
        Dim cmdBuilder As OleDbCommandBuilder = New OleDbCommandBuilder(myAdapter)
        Dim changes As DataTable = myTable.GetChanges
        If changes IsNot Nothing Then
            myAdapter.Update(myTable)
        End If
        myTable.AcceptChanges()
End Sub