VB.NET - Array of Integers needs to be instantiated, how to? - vb.net

First try
Dim holdValues() As Integer 'Doesn't Work
holdValues(1) = 55
Second try
Dim holdValues(-1) As Integer 'Gives me Index was outside the bounds of the array.
holdValues(1) = 55
I'm trying to do something similar to
Dim myString(-1) As String
But apparently this doesn't apply to integer arrays. I don't know what the size of the array will be, it wont get smaller but it will grow larger.
Any help will be appreciated, thank you!

You could use the Initializers shortcut:
Dim myValues As Integer() = New Integer() {55, 56, 67}
But if you want to resize the array, etc. then definately have a look at a List(Of Integer):
'Initialise the list
Dim myValues As New System.Collections.Generic.List(Of Integer)
'Shortcut to pre-populate it with known values
myValues.AddRange(New Integer() {55, 56, 57})
'Add a new value, dynamically resizing the array
myValues.Add(32)
'It probably has a method do do what you want, but if you really need an array:
myValues.ToArray()

you add the number to
holdValues(x) //x+1 will be size of array
so something like this
Dim array(2) As Integer
array(0) = 100
array(1) = 10
array(2) = 1
you can re-allocate the array to be bigger if needed by doing this.
ReDim array(10) as Integer
you'll have to add in your code when you should make your array bigger. You can also look into lists. Lists take care of this issue automatically.
here's some info on Lists: http://www.dotnetperls.com/list-vbnet
Hope this helps.
Also a link for general knowledge on arrays http://www.dotnetperls.com/array-vbnet

Related

Creating a new String Array from another

I have an array of integers (dfArray) and would like to create a new second String array which consists of the integers and appending "G" to the beginning. What's the best way to go about this? I was thinking of For Each but couldn't get it to work. Thanks in advance.
Set dfArray = [dff]
Set dfArray2 = ["G" & dff] 'incorrect but you get the idea?
Dim dfArray() As Variant
Dim dfArray2() As String
dfArray = [dff].Value
ReDim dfArray2(UBound(dfArray)) As String
Dim i As Double
For i = 1 To UBound(dfArray) Step 1
dfArray2(i) = "G" & dfArray(i, 1)
Next i
Anyways, from my personal point of view, I don't like to asign a complete Range into Array, only if needed. I prefer to loop using Lbound or Ubound and control the array all the time. To asign a range into an Array, you need the Array variable to be Variant type, and also, you can't use Preserve easily. Check this question for more info
Issues about Variant Arrays

how to get the specify items in byte() array in VB

I am working on the VB.NET. I have two arrays need to compare and output the remainder of the longer array. I just simplify my question as following code:
Dim array1 As Byte() = {&H01, &H22,&H10,&HBC,&HA2,&H01,&H00,&HA6,&H02,&HBB,&H33,&H11,&HB2,&H01}
Dim array As Byte() = {&H01, &H22,&H10,&HBC,&HA2,&H01,&H00,&HA6,&H02,&HBB,&H33,&H11,&HB2,&H02,&H77,&H44,&HBF}
Dim remainder As Byte()
IF(array1.Length< array2.Length) then
Dim remainderLength = array2.Length- array1.Length
For...
'''array1.Length =14
'''array2.Length =17
'''write the code to sign the last 3 Hex values into new array remainder and output the remainder
Next
the remainder length might be changed to other sizes, 100, 200 or more. I tried the Item()function and IndexOf()function, and didn't get the result. Please help to write the left code. The final result I want remainder = {&H77,&H44,&HBF}
thank you very much for any comments.
The simplest approach would be to use LINQ's Skip extension method.
For Each b As Byte In array.Skip(array1.Length)
Console.Write(b)
Next
Or:
Dim remainder As Byte() = array.Skip(array1.Length).ToArray()
You may also want to consider using the Array.Copy method which allows you to pass the starting index as an argument:
Array.Copy(array, array1.Length, remainder, 0, array.Length - array1.Length)
Or, if all else fails, it's always possible to access each item in the array by index:
For i As Integer = array1.Length to array.Length
Console.Write(array(i))
Next

2D arrays throws index out of bound exception

I'm making a program and I keep getting the error Index was outside the bounds of the array and I can't figure out why. I tried all the different versions of setting up my 2D array.
Here is how I have it set up now
Dim dataArray(,) As Array = New Array(,) {{}}
Here is my loop for it
Dim x As Integer
Dim DT As DataTable
Dim TA As New DSOldOrdersTableAdapters.TA
DT = getOldOrders()
For x = 0 To DT.Rows.Count - 1
dataArray(0, x) = DT.Rows(x).Item("SO")
dataArray(1, x) = (DT.Rows(x).Item("Customer"))
dataArray(2, x) = (DT.Rows(x).Item("ShipBy"))
Next
You are declaring an array with a length of 0. That means that it will be unable to hold any data. All indexes will be out of range. Arrays do not automatically grow as items are added to them. As such, arrays should typically only be used in situations where the size of the array is fixed (unchanging). For instance:
Dim dataArray(2, 2) As Object ' Creates a 3x3 array of objects
If you want it to automatically grow as items are added, you would typically want to use a List(Of T) rather than an array. For instance:
Public Class MyItem
Public Property SO As Object
Public Property Customer As Object
Public Property ShipBy As Object
End Class
' ...
Dim dataList As New List(Of MyItem)()
' ...
Dim item As New MyItem()
item.SO = DT.Rows(x).Item("SO")
item.Customer = DT.Rows(x).Item("Customer")
item.ShipBy = DT.Rows(x).Item("ShipBy")
dataList.Add(item)
' ...
Label1.Text = dataList(1).SO
Or, if you insist on using an array to store each item, you can make a list of 1D arrays, like this:
Dim dataList As New List(Of Object())()
' ...
dataList.Add(
{
DT.Rows(x).Item("SO"),
DT.Rows(x).Item("Customer"),
DT.Rows(x).Item("ShipBy")
})
' ...
Label1.Text = dataList(1)(0)
As #Steven Doggart said (and beat me up to one minute with the answer) you are declaring an array, but you don't give the dimension length. You have two options:
specify the array dimension size at the declaration
or use Redim to set the (dimension) size of the array
In your case one solution could look like this:
Dim dataArray(,) As Array = New Array(3, DT.Rows.Count) {{}}
Or like this:
Dim dataArray(,) As Array = New Array(,) {{}}
Redim dataArray(3, DT.Rows.Count)
Dim x As Integer
Dim DT As DataTable
Dim TA As New DSOldOrdersTableAdapters.TA
DT = getOldOrders()
For x = 0 To DT.Rows.Count - 1
dataArray(0, x) = DT.Rows(x).Item("SO")
dataArray(1, x) = (DT.Rows(x).Item("Customer"))
dataArray(2, x) = (DT.Rows(x).Item("ShipBy"))
Next
Have a look at this MSDN Article - How to: Initialize an Array variable in VB.NET.
Dim dataArray(,) As Array = New Array(,) {{}}
This creates a two-dimensional array of Array, i.e. a two-dimensional array where each element is an Array. It's then initialized to an array containing a single, empty Array element. I expect this is not what you intended.
Since you never ReDim your array anywhere in the code to alter its dimensions, it remains a two-dimensional array whose first dimension is length 1, and whose second dimension is length zero.
When you try to run
dataArray(0, x) = DT.Rows(x).Item("SO")
The second dimension of the array has length zero, so it cannot hold a value. Thus you get an "index out of range" exception. If this did not happen, you would probably get another exception, because DT.Rows(x).Item("SO") probably is not an Array.
It would probably be easier to leave the data in the DataTable, and read from it whenever needed. Otherwise, I think your intent was to do something like:
Dim dataArray(0 To 3, -1) As Object 'Temporarily create a 2D Object array
'...load the DataTable
ReDim dataArray(0 to 3, 0 To DT.Rows.Count - 1) 'Redimension the array to the proper size.
'...rest of code

How to assign a value to an array from a combobox

The code I have is:
Dim Dbase() As String = Nothing
Dbase(0) = Db_ComboBox.Text
I have declared Dbase as array and assigned Nothing, Db_ComboBox is a combobox.
For that assignment statement, I'm getting the following error: "Reference 'Dbase' has a value of 'Nothing'"
What is the reason for this error, and how can I take the value from the combobox and save it in the array?
You need to change this:
Dim Dbase() As String = Nothing
to this (declare an array of 1 element):
Dim Dbase(0) As String
And then this line will work:
Dbase(0) = Db_ComboBox.Text
If you need to change your array size you can use Redim or Redim preserve, as required.
If you anticipate contents of Dbase to change often, I am all with #Joel's suggestion about switching to List(Of String) instead of handling array sizes manually.
Let's look at your code:
Dim Dbase() As String = Nothing
Dbase(0) = Db_ComboBox.Text
Especially the first line. That first line creates a variable that can refer to an array, but the = Nothing portion explicitly tells it, "Do not create a real array here yet". You have, effectively, a pointer that doesn't point to anything.
I get here that what you really need is a List collection that you can append to over time:
Dim Dbase As New List(Of String)()
Dbase.Add(Db_ComboBox.Text)
Dbase() IS NOTHING. Look at this example:
cargoWeights = New Double(10) {}
atmospherePressures = New Short(2, 2, 4, 10) {}
inquiriesByYearMonthDay = New Byte(20)()() {}
That's how you declare arrays.
More examples: http://msdn.microsoft.com/en-us/library/vstudio/wak0wfyt.aspx

VB.NET Multi-Dimentional Array

Alright, so I'm used to PHP where I can declare a multi-level array like $something[0][1] = "test";. I need to be able to accomplish the same thing, but I'm using VB.NET. How would I do this?
And sorry if this isn't what a multi-dimentional array is, I might be wrong at what it's called but that's what I want to do.
Thanks!
Multidimensional array in VB.Net...
Dim twoDimensionalArray(10, 10) As String
twoDimensionalArray(0, 1) = "test"
I rarely use arrays, however. More elegant solutions can typically be achieved using Lists, Dictionaries, or combinations of the two.
Update .
The (10, 10) is the upper bound of the array (the size is actually 11, 0 through 10). If you don't specify the bounds, you have to Redim Preserve the array when you want to add to it. That's one good thing about lists, you don't have to specify an initial size and you can add to them freely.
Here's a quick example of a list of lists.
Dim listOfLists As New List(Of List(Of String))
listOfLists.Add(New List(Of String)(New String() {"a", "b", "c"}))
listOfLists.Add(New List(Of String)(New String() {"d", "e", "f"}))
listOfLists.Add(New List(Of String)(New String() {"g", "h", "i"}))
'listOfLists(0)(0) = "a"
'listOfLists(0)(1) = "b"
'listOfLists(2)(1) = "h"
Just a plain sample with dynamic resizing of the array
Dim arr(0)() As String '** array declaration
For i As Integer = 0 To 100 '** Outer loop (for the 1st dimension)
For j As Integer = 0 To 1 '** inner loop (for the 2nd dimension)
ReDim Preserve arr(i) '** Resize the first dimension array preserving the stored values
ReDim Preserve arr(i)(j) '** Resize the 2nd dimension array preserving the stored values
arr(i)(j) = String.Format("I={0},J={1}", i, j) '** Store a value
Next
Next
In .NET Arrays are usually static and won't be automatically resized. (As for example in Javascript etc.) Therefore it's necessary to manually resize the array each time you want to add a new item, or specify the size at the beginning.