【问题标题】:Deleting SQL Rows and DataGrid Rows in Visual Basic在 Visual Basic 中删除 SQL 行和 DataGrid 行
【发布时间】:2014-02-22 06:23:50
【问题描述】:

又是我 :)

我正在尝试从 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.

希望有人能解释一下。

提前致谢。

【问题讨论】:

    标签: sql visual-studio datagridview


    【解决方案1】:

    该错误意味着,当您尚未将任何参数添加到 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
    .......
    

    【讨论】:

    • 你美!!再次感谢伙计。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-03
    • 1970-01-01
    • 2012-09-19
    • 1970-01-01
    • 2012-02-11
    相关资源
    最近更新 更多