Shafiq Izwan Shafiq Izwan - 3 months ago 6
Vb.net Question

How to display non-empty array only (VBnet)

I have an array as follows:

If iAdvanceMonthNum = 1 Then
iAdvanceMonthName(1) = "January"
ElseIf iAdvanceMonthNum = 2 Then
iAdvanceMonthName(2) = "February"
ElseIf iAdvanceMonthNum = 3 Then
iAdvanceMonthName(3) = "March"
ElseIf iAdvanceMonthNum = 4 Then
iAdvanceMonthName(4) = "April"
ElseIf iAdvanceMonthNum = 5 Then
iAdvanceMonthName(5) = "May"
ElseIf iAdvanceMonthNum = 6 Then
iAdvanceMonthName(6) = "June"
ElseIf iAdvanceMonthNum = 7 Then
iAdvanceMonthName(7) = "July"
ElseIf iAdvanceMonthNum = 8 Then
iAdvanceMonthName(8) = "August"
ElseIf iAdvanceMonthNum = 9 Then
iAdvanceMonthName(9) = "September"
ElseIf iAdvanceMonthNum = 10 Then
iAdvanceMonthName(10) = "October"
ElseIf iAdvanceMonthNum = 11 Then
iAdvanceMonthName(11) = "November"
ElseIf iAdvanceMonthNum = 12 Then
iAdvanceMonthName(12) = "December"
End If


Let say the array will be:
iAdvanceMonth(9) = "September" and
iAdvanceMonth(10) = "October"

while the other array will be null. What I want to achieve is that I want to display "September" and "October".

The code to display the string that I have done so far:

Dim display As String = String.Empty
For i As Integer = 1 To iAdvanceMonthName.Length - 1
If Not String.IsNullOrEmpty(iAdvanceMonthName(i)) Then
display = iAdvanceMonthName(i)
End If
Next


However, the output will only be "October" as the code will take the latest array. Can I get some hints or tips on how to solve this. Thanks a lot.

Answer

try this code

    Dim display As String = String.Empty
    For i As Integer = 1 To iAdvanceMonthName.Length - 1
        If Not String.IsNullOrEmpty(iAdvanceMonthName(i)) Then
            display = display & iAdvanceMonthName(i) & " And "
        End If
    Next
    If Not String.IsNullOrEmpty(display) Then display = Left(display, display.Length - 5)