system.data.sqlclient.row'在循环中抛出数据网格视图在vb.net中出现错误

时间:2014-01-08 06:01:14

标签: vb.net datagridview

我正在开发vb.net windows应用程序
我有一个数据网格视图..在更新按钮我写了这样的代码

Private Sub btnupdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnupdate.Click

        Dim cid As Integer
        Dim dtid As Integer
        Dim cmpname As String
        Dim dtname As String
        Dim dtPhone As String
        Dim dtEmail As String
        For i As Integer = 0 To gv.RowCount - 2
            Dim rv = DirectCast(bSource.Current, DataRowView)
            cid = rv.Row.Field(Of Integer)("Cid")
            dtid = rv.Row.Field(Of Integer)("dtId")
            cmpname = rv.Row.Field(Of String)("CompanyName")
            dtname = rv.Row.Field(Of String)("dtName")
            dtPhone = rv.Row.Field(Of String)("dtPhone")
            dtEmail = rv.Row.Field(Of String)("dtEmail")

            adapter.UpdateCommand = New SqlCommand("UPDATE CompanyMaster_tbl SET CompanyName = @CompanyName", con)
            adapter.UpdateCommand = New SqlCommand("update DepartmentMaster_tbl set dtName = @dtName,dtPhone = @dtPhone,dtEmail = @dtEmail  where dtId=@dtid", con)
            adapter.UpdateCommand.Parameters.AddWithValue("@Cid", cid)
            adapter.UpdateCommand.Parameters.AddWithValue("@CompanyName", cmpname)
            adapter.UpdateCommand.Parameters.AddWithValue("@dtId", dtid)
            adapter.UpdateCommand.Parameters.AddWithValue("@dtName", dtname)
            adapter.UpdateCommand.Parameters.AddWithValue("@dtPhone", dtPhone)
            adapter.UpdateCommand.Parameters.AddWithValue("@dtEmail", dtEmail)
            adapter.UpdateCommand.ExecuteNonQuery()
        Next
End Sub

在这段代码中我面临一个问题..同时如果我在数据网格视图中更新了3行..这只影响了最后更新的行..这段代码中缺少了什么代码..我试试代码就像这也是

For Each row As DataGridViewRow In gv.Rows
        ...
        adapter.UpdateCommand.Parameters.AddWithValue("@Cid", Row.Cells("cid").Value)
        ...
        adapter.UpdateCommand.ExecuteNonQuery()  
    Next

那次收到错误: system.data.sqlclient.row'在此上下文中无法访问,因为它是“朋友”

任何帮助都非常感谢,提前致谢。

1 个答案:

答案 0 :(得分:0)

在您的第一个版本中将代码更改为:

...
For i As Integer = 0 To gv.RowCount - 2
    Dim rv = DirectCast(gv.Rows(i).DataBoundItem, DataRowView)
    cid = rv.Row.Field(Of Integer)("Cid")
...

它仅在最后一行更新,因为在每个循环中 你总是得到同一行Dim rv = DirectCast(bSource.Current, DataRowView)
现在它将遍历所有行