I am new to coding with visual basic.
Recently, I was tasked by my professor to write a programme that allows the user to enter five words. The words then should be sorted and displayed in alphabetical order.
To do this I decided the best approach would be to use an array.
My thinking was that if I created a counter at the start, I can create a different value for each column of the array when a button is clicked.
If the array exceeds five I have a message box pop-up that resets the code (although I realise I will also have to clear the contents of the array).
My problem arises in displaying the array. I have looked for solutions online, and none have helped me as of yet.
I need to sort the array into alphabetical order and then display it in a label box (lbl_DisplayArray). As I do not know the values of the array, this has proved tricky.
My code is below:
Public Class Form1
Dim i As Integer = 0
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim Array(4) As String
Array(i) = txt_UserWords.Text
Private Sub btn_Next_Click(sender As Object, e As EventArgs) Handles btn_Next.Click
i += 1
If i >= 5 Then
i = 0
MsgBox("Array Limit Exceeded. Code Reset")
txt_UserWords.Text = ""
Private Sub btn_Sort_Click(sender As Object, e As EventArgs) Handles btn_Sort.Click
You'd be better off using
private myList as new List(of String).
Then to sort them you just call the .Sort() method. Just call
.Add(txt_userWords.Text) to add the new string and use .Count to see how many of them you have.
When you're adding them to the label you can use
lbl_DisplayArray.Text = String.Join(vbCrLf, myList)
You'll need the list of to be a member of the class instead of a local variable (as you have declared Array). This will keep it alive and allow you to access it in other methods.
---------- edit ----------
Public Class Form1 private myList as new List(of String) Private Sub btn_Next_Click(sender As Object, e As EventArgs) Handles btn_Next.Click If myList.Count >= 5 Then myList.Clear Else myList.add(txt_UserWords.Text) End If txt_UserWords.Text = "" End Sub Private Sub btn_Sort_Click(sender As Object, e As EventArgs) Handles btn_Sort.Click myList.Sort() lbl_DisplayArray.Text = String.Join(vbcrlf, myList) End Sub End Class