This one is working but it only output a sequence of number in ascending order even if the First Input is higher than the Second Input.
Here is what I want to happen
Ascending Order when
First Input: 2
Second Input: 8
Result 2, 3, 4, 5, 6, 7, 8
Descending Orden when
First Input: 9
Second Input: 6
Result: 9, 8, 7, 6
Private Sub btnAccept_Click(sender As Object, e As EventArgs) Handles btnAccept.Click
Dim A = txtstart.Text
Dim B = txtend.Text
Dim Start, Ending As Integer
If A < B Then
Start = A
Ending = B
Else
Start = B
Ending = A
End If
While Start <= Ending
lblbetween1.Text = lblbetween1.Text & Start & " , "
Start = 1
End While
End Sub
CodePudding user response:
With a For
loop, you can choose the increment, so you can check which order the numbers are in and set the increment appropriately, for example:
Option Strict On
Imports System.Text
' ....
Private Sub btnAccept_Click(sender As Object, e As EventArgs) Handles btnAccept.Click
Dim a = Integer.Parse(txtStart.Text)
Dim b = Integer.Parse(txtEnd.Text)
Dim inc As Integer = -1
If a < b Then
inc = 1
End If
Dim sb As New StringBuilder()
For i = a To b Step inc
sb.Append(i & " , ")
Next
lblbetween1.Text = sb.ToString()
End Sub
Fortunately, this still works if the numbers are equal, so there is no need for a special case for that.
It's better to use a StringBuilder to concatenate lots of strings, instead of just using &
on lots of strings or the content of a control.
Option Strict On
makes sure that the program doesn't try to do things with possibly unexpected results such as adding a number to a string. You should set it as the default for new projects.
CodePudding user response:
You could do something like this:
Will need to add
Imports System.Linq
and then
Dim a = 10I
Dim b = 15I
Dim start = Math.Min(a, b)
Dim count = Math.Max(a, b) - start
Dim series = Enumerable.Range(start, count 1).ToList
If b < a Then
series.Reverse()
End If
Dim result = String.Join(",", series)