循环遍历datagrid值并使用其他datagridview vb.net的值

时间:2017-02-02 09:21:21

标签: vb.net datagridview foreach datagrid

我有一个datagridview,我想获取模型列的值并获取其他datagridview的模型计数,但我不知道如何遍历第一个数据网格中的单元格值。

This is the screenshot

我想要的是让右侧的count datagrid也有2列。这是我的代码:

  Private Sub jessy()
    Dim count As Integer = 0
    Dim a = requestDatagridview.Rows.Count
    MsgBox(a)
    For Each row As DataGridViewRow In requestDatagridview.Rows
        Label1.Text = row.Cells("model").Value
        conn = New MySqlConnection
        conn.ConnectionString = "server=127.0.0.1; port=3306; username=root; password=""; database= atos_db"

        Dim dbDataset1 As New DataTable
        Dim sda1 As New MySqlDataAdapter
        Dim bsource1 As New BindingSource
        Try
            conn.Open()
            Dim query As String
            query = "select count(serial_no) as 'Count' from atos_db.equip_tbl left join atos_db.itemdetails_tbl on equip_tbl.itemdetails_id=itemdetails_tbl.itemdetails_id left join atos_db.brand_tbl on itemdetails_tbl.brand_id = brand_tbl.brand_id left join atos_db.item_tbl on brand_tbl.item_id=item_tbl.item_id where model='" & a & "'"

            comm = New MySqlCommand(query, conn)

            sda1.SelectCommand = comm
            sda1.Fill(dbDataset1)
            bsource1.DataSource = dbDataset1
            countDatagridview.DataSource = bsource1
            sda1.Update(dbDataset1)
            conn.Close()
        Catch ex As MySqlException
            MessageBox.Show(ex.Message)
        Finally
            conn.Dispose()
        End Try
    Next

End Sub

1 个答案:

答案 0 :(得分:0)

以下代码可以为您提供帮助:

' Create a variable to store your value (example qty)
Dim total As Integer = 0

' Loop through your datagridview rows.
For i As Integer = 0 To dtgv.Rows.Count - 1 
' Add the qty value of the current row to total
total = total + dtgv.Rows(i).Cells(4).Value
Next

' Then, modify the value of the second dtgv
dtgv2.Rows(0).Cells(0).Value = total