Find and sum value of a datagridview column in vb.

2020-05-11 02:15发布

问题:

I want to find and sum qty value of searched id in data grid view column am using this code

Dim tqty As Double
For Each row As DataGridViewRow In dgv.Rows
    If row.Cells.Item(0).Value = cmbItemCode.Text Then
        tqty += row.Cells.Item(4).Value
        Textbox1.text=tqty
        Exit For
    End If
Next

The problem is that Textbox1 shows only one top searched row value. For example

id     item name    qty
1      abc           4
2      xyz           10
1      abc           10

Textbox1 shows the Result only 4.

回答1:

As soon as you hit the first value, you exit the for statement. Therefore you never get pass the first value. Erase the Exit For it should work.



回答2:

If DataGridView2.RowCount > 1 Then Dim tqty As Integer = 0

        'if you have the other column to get the result you  could add a new one like these above 
        For index As Integer = 0 To DataGridView2.RowCount - 1
            amount += Convert.ToInt32(DataGridView2.Rows(index).Cells(2).Value)

            'if you have the other column to get the result you  could add a new one like these above (just change Cells(2) to the one you added)
        Next
        TextBox1.Text = tqty


标签: vb.net