-
Dynamically setting integer arrays
OK, this is most likely very easy for most of you guys out here, but It is proving most difficult to me.
IN VB.net, i am trying to add to an integer array. Since I do not know how many items will be in this array when the user is finished I can not set the number of items in the array, i.e. dim intNumber(3) as integer.
I am trying to write a procedure that will insert a number into the next available dimension of the integer array.
When I use array.getLength, or array.getupperbound, or array.lenght i keep getting errors about how I can't do this to a null array. I need my program to add the first item to the array once the user enter to correct information, and the next item to the array when they do it again, and so forth until they are done. How can this be accomplished best? Thanks for your help.
-
The simplest solution is to use an ArrayList (from the System.Collections namespace); you may simply Add items to an ArrayList, and it grows to accomodate them.
If you must use an array rather than an ArrayList, pick an arbitrary initial size, say, 10 elements, then use ReDim Preserve to grow the array as necessary:
Code:
' Create space for 10 elements,
' numbered 0 through 9
Dim intNumber(9) As Integer
' Keep track of maximum index number
Dim maxIndex As Integer
' Now we're going to add 25 elements
' to the array
For I As Integer = 0 To 24
' If array is full...
If maxIndex = UBound(intNumber) Then
' Make room for 10 more elements
ReDim Preserve intNumber(maxIndex + 10)
End If
intNumber(maxIndex) = I
' Increment max index
maxIndex += 1
Next
' Shrink array to actual number
' of elements
ReDim Preserve intNumber(maxIndex - 1)
Phil Weber
http://www.philweber.com
Please post questions to the forums, where others may benefit.
I do not offer free assistance by e-mail. Thank you!
Similar Threads
-
By eduardoms in forum Security
Replies: 2
Last Post: 05-06-2005, 10:26 AM
-
Replies: 146
Last Post: 08-12-2002, 10:40 PM
-
By Rudolph Jones in forum VB Classic
Replies: 6
Last Post: 05-17-2001, 11:44 PM
-
By Rudolph Jones in forum VB Classic
Replies: 0
Last Post: 05-16-2001, 05:24 PM
-
By Kunal Sharma in forum VB Classic
Replies: 2
Last Post: 04-25-2000, 03:45 PM
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
|
Top DevX Stories
Easy Web Services with SQL Server 2005 HTTP Endpoints
JavaOne 2005: Java Platform Roadmap Focuses on Ease of Development, Sun Focuses on the "Free" in F.O.S.S.
Wed Yourself to UML with the Power of Associations
Microsoft to Add AJAX Capabilities to ASP.NET
IBM's Cloudscape Versus MySQL
|
Bookmarks