如何在vb.net windows应用程序中循环抛出数据网格视图中的所有行

时间:2014-01-07 11:44:16

标签: vb.net winforms datagridview

我有一个数据网格视图..在更新按钮我写了这样的代码

Dim cid As Integer
        Dim dtid As Integer
        Dim cmpname As String
        Dim dtname As String
        Dim dtPhone As String
        Dim dtEmail As String
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()

我是datagridview.same时的新手,如果我更新多行,它会影响最后更新的行,所以我需要循环抛出datagridview中的所有行。我可以实现这一点..

所以我像这样给出了循环内的整个代码

For Each row As DataGridViewRow In gv.Rows
    'my code here
Next

但是还要更新上次更新的行?提前致谢

2 个答案:

答案 0 :(得分:0)

For Each row As DataGridViewRow In gv.Rows
Cmd = new Sqlcommand("insert into tblemp (empid,empval) values("& rw.cells(0).value &",'"& rw.cells(1).value&"')",con)
Next

答案 1 :(得分:0)

尝试使用'row'而非Current:

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