|
-
Nov 18th, 2011, 11:39 AM
#1
Thread Starter
New Member
Arrays
When I click the Add button is saves the word entered to an array and then when Show is clicked it shows the words in the array. However if I enter 5 words and then click show it'll show the 5 words and then if I add another few words and click show it'll only show the few added words and not the 5 original words entered.
Code:
Public Class Form1
Dim wordList(19) As String
Dim k As Integer
Private Sub cmdAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdAdd.Click
If k < 20 Then
wordList(k) = txbWord.Text
End If
If k = 19 Then
cmdAdd.Enabled = False
End If
k = k + 1
' txbWord.Clear()
' doesnt include 20th word in list
End Sub
Private Sub cmdShow_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdShow.Click
lstBox.Items.Clear()
Array.Sort(wordList)
Dim i As Integer
lstBox.Items.Add("Index Word")
For i = 0 To wordList.GetUpperBound(0)
lstBox.Items.Add(CStr(i+1) & " " & wordList(i))
Next
End Sub
The array has a limit of 20 words
Last edited by ryan1234; Nov 18th, 2011 at 11:44 AM.
-
Nov 18th, 2011, 12:08 PM
#2
Re: Arrays
First up, why all the empty space in the code? You're just making it harder for us to read it, and therefore help you. If you want people to help you, it's generally not a good idea to make it unnecessarily harder for them to do so. It would have taken you a few seconds to clean up that code. You really should be cleaning it up for your own sake anyway.
As for the question, the reason is not immediately obvious but there are two things that you should think about:
1. Have you actually debugged the code? When code doesn't work as you expect, reading it is not always enough. You often need to watch it in action. Set a breakpoint (F9) at the top of a section of code and when it's hit, step through the code line by line (F10). You can then check the state of your variables, etc, at each step and make sure that it is what you think it should be. As soon as you find that it's not, you've found the issue.
2. Should you really be using an array at all? Unless this is an assignment that requires you to use an array, the answer is no. You should be using a collection, specifically a List(Of String) in situations like this. That way there is no need to muck around with tracking indexes, etc.
-
Nov 18th, 2011, 12:13 PM
#3
Member
Re: Arrays
Try this:
vb Code:
Static k As Integer = 0
If k <= 19 Then
wordList(k) = txbWord.Text
k += 1
Else
SomeOtherControl.Focus
cmdAdd.Enabled = False
End If
Chris.
-
Nov 18th, 2011, 12:16 PM
#4
Member
Re: Arrays
Apologies jmcilhinney, your reply was posted as I was writing mine - I'm not trying to work at cross purposes to you.
C.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|