我再次:)
我正在尝试从DataGridView中删除行,并同时从SQL数据库中删除相同的值。
这是我到目前为止所做的事情,这是我刚刚在Google上采访的内容:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim myconnect As New SqlClient.SqlConnection
myconnect.ConnectionString = "Data Source=.\INFLOWSQL;Initial Catalog=RioDiary;Integrated Security=True"
Dim mycommand As SqlClient.SqlCommand = New SqlClient.SqlCommand()
mycommand.Connection = myconnect
myconnect.Open()
mycommand.CommandText = "DELETE FROM MyDiary" + DataGridView1.CurrentRow.Cells(0).Value + "'"
For Each row As DataGridViewRow In DataGridView1.SelectedRows
mycommand.Parameters(1).Value = row.Cells(0).Value
mycommand.ExecuteNonQuery()
DataGridView1.Rows.Remove(row)
Next row
myconnect.Close()
End Sub
显然不起作用。我得到的错误是:
Invalid index 1 for this SqlParameterCollection with Count=0.
希望有人能说清楚。
提前致谢。
答案 0 :(得分:0)
该错误意味着,当您尚未将任何参数添加到mycommand
时,您尝试访问索引1中的参数(索引1表示第二个参数。从零开始的索引)。
假设DataGridViewRow
中的第一个单元格包含在SQL参数中使用的id,您可以尝试这样的事情:
.......
mycommand.CommandText = "DELETE FROM MyDiary WHERE Id = @Id"
'add parameter once
mycommand.Parameters.Add("@Id", SqlDbType.VarChar)
For Each row As DataGridViewRow In DataGridView1.SelectedRows
'set parameter value to Id column of current row
mycommand.Parameters(0).Value = row.Cells(0).Value
mycommand.ExecuteNonQuery()
DataGridView1.Rows.Remove(row)
Next row
.......