joe joe - 1 month ago 4
Vb.net Question

Creating a string list of values in a datatable

I'm trying to create a list of rates in a program where the rates are running out a month from today, so that a reminder can be sent to the user to extend them. My code for doing so is below

Try
Dim rDt As New DataTable
Dim r1Dt As New DataTable

Using rDa = New OleDbDataAdapter("SELECT DISTINCT [Comm_Code] FROM [Acquisition Commission] WHERE DateTo=?", con)
rDa.SelectCommand.Parameters.Add("@date", OleDbType.Date).Value = Date.Today.AddMonths(1)
rDa.Fill(r1Dt)
End Using

Dim r2Dt As New DataTable
Using r2Da = New OleDbDataAdapter("SELECT DISTINCT [Comm_Code] FROM [Commission Rates] WHERE DateTo=?", con)
r2Da.SelectCommand.Parameters.Add("@date", OleDbType.Date).Value = Date.Today.AddMonths(1)
r2Da.Fill(r2Dt)
End Using

Dim r3Dt As New DataTable
Using r3Da As New OleDbDataAdapter("SELECT DISTINCT [Comm_Code] FROM [Customer Special Rates] WHERE DateTo=?", con)
r3Da.SelectCommand.Parameters.Add("@date", OleDbType.Date).Value = Date.Today.AddMonths(1)
r3Da.Fill(r3Dt)
End Using

rDt = r1Dt.Copy
rDt.Merge(r2Dt)
rDt.AcceptChanges()
rDt.Merge(r3Dt)
rDt.AcceptChanges()

If rDt.Rows.Count > 0 Then
Dim rates As String = ""
For Each dr As DataRow In rDt.Rows
rates = dr.Item("Comm_Code") & ", "
Next
If MsgBox("The following rates; " & rates & "are set to expire in 1 month. Would you like to automatically extend these rates by 6 months?", MsgBoxStyle.YesNo, "Extend Rates") = MsgBoxResult.No Then

Else


However, when stepping through this code, I can see that
rDt
has 3 rows (As I expected, 1 rate from each table as a test), but the
For Each
loop only iterates once, so only 1 of the 3 items is concatenated onto the string.

Why is this, and how do I fix it?

Answer

You override rates each time.

rates = dr.Item("Comm_Code") & ", "

You need to change it to

rates &= dr.Item("Comm_Code") & ", "

Be wary of the extra comma.

Comments