我的更新按钮只更新第一个选中的行而不是其他

时间:2011-02-01 14:42:14

标签: asp.net vb.net gridview sqldatasource

我让数据库更新,但它只针对第一行选择而不是其他人。

     Protected Sub btnUpdate_Click(ByVal sender As Object, ByVal e As EventArgs)

    For Each row As GridViewRow In GridView6.Rows
        ' Selects the text from the TextBox
        Dim selectedcheck As CheckBox = CType(row.FindControl("chkselect"), CheckBox)

        If selectedcheck.Checked = True Then
            Dim id As Label = CType(row.FindControl("id"), Label)
            cmd.Parameters.AddWithValue("@id", id.Text)
            cmd.Parameters.AddWithValue("@compby", txtagent.Text)
            cmd.Parameters.AddWithValue("@compdate", lbldate.Text)
            cmd.Parameters.AddWithValue("@comments", txtcomments.Text)


            cmd.CommandText = "dbo.updatetasks"
            cmd.CommandType = CommandType.StoredProcedure
            cmd.Connection = conn

            conn.Open()

            cmd.BeginExecuteNonQuery()

            conn.Close()
        End If

    Next

End Sub

enter image description here

UPDATE dashboardtasks
       SET compby = @compby,
           comments = @comments,
           compdate = @compdate


       WHERE id = @id;

1 个答案:

答案 0 :(得分:1)

我希望以下内容有效:

  Protected Sub btnUpdate_Click(ByVal sender As Object, ByVal e As EventArgs)

    For Each row As GridViewRow In GridView6.Rows
        ' Selects the text from the TextBox
        Dim selectedcheck As CheckBox = CType(row.FindControl("chkselect"), CheckBox)

        If selectedcheck.Checked = True Then
            Dim id As Label = CType(row.FindControl("id"), Label)
            cmd.Parameters.Clear()     '<---- Stop adding more and more parameters
            cmd.Parameters.AddWithValue("@id", id.Text)
            cmd.Parameters.AddWithValue("@compby", txtagent.Text)
            cmd.Parameters.AddWithValue("@compdate", lbldate.Text)
            cmd.Parameters.AddWithValue("@comments", txtcomments.Text)


            cmd.CommandText = "dbo.updatetasks"
            cmd.CommandType = CommandType.StoredProcedure
            cmd.Connection = conn

            conn.Open()

            cmd.ExecuteNonQuery() '<--- Don't use the asynchronous variant if you're not going to obey the contract

            conn.Close()
        End If

    Next

End Sub

如果你使用ExecuteNonQuery的同步变体,或者遵守异步方法的合同(你必须调用{{1}),你会得到一个很好的例外,告诉你你做错了什么。发现SQL调用的结果。