iDev
iDev

Reputation: 478

looping through a data table vb

I'm trying to loop through a data table that has multiple values for my constraint. How can I keep the first value and add together all the other values that match my constraint.

For i = 0 To ds.Tables(0).Rows.Count - 1

            If ds.Tables(0).Rows(i).Item("TEND_POS_ID") = 8 Then

              'This only returns the last value  
              'Value 1 = 2
              'Value 2 = 7.5
              'should = 9.5 but it is showing 7.5                  

             tmpCoupon = ds.Tables(0).Rows(i).Item("TENDER_AMT")
            End If
        Next
        txtCoupon.Text = tmpCoupon

Upvotes: 2

Views: 17171

Answers (1)

Steve
Steve

Reputation: 216343

If I understand your question correctly, you need to add the values of TENDER_AMT where the value in TEND_POS_ID is 8. If this is the case you could use the Select method of the DataTable

 Dim rows = ds.Tables(0).Select("TEND_POS_ID = 8")
 for each r in rows
    tmpCoupon += Convert.ToDecimal(r("TENDER_AMD"))
 Next

However, rembember that this kind of work (SUM a column grouping by another column) is usually better resolved by the query that you submit to the database. Something like this:

SELECT TEND_POS_ID, SUM(TENDER_AMD) FROM Table1 GROUP BY TEND_POS_ID

Upvotes: 2

Related Questions