Getting exception while initializing the value in array dynamically [duplicate] - arrays

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 6 years ago.
I am beginner in VB. I am trying to find the indexes of selected values of ListBox1 and print those indexes in ListBox2. I am not specifying the length of array. I want it to take the values dynamically. Here is the code..
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
Dim a() As Integer
Dim b As Integer = 0
For x As Integer = 0 To ListBox1.Items.Count - 1
If ListBox1.GetSelected(x) = True Then
a(b) = x
b = b + 1
End If
Next
For x As Integer = 0 To a.Length - 1
ListBox2.Items.Add(a(x))
Next
End Sub
The exception I am getting at line a(b) = x is as follows
NullReferenceException was unhandled
Object reference not set to an instance of an object.
Can you kindly help me in this?

You either remove a() completely or else define a size for it:
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
ListBox2.Items.Clear()
For x As Integer = 0 To ListBox1.Items.Count - 1
If ListBox1.GetSelected(x) = True Then
ListBox2.Items.Add(x)
End If
Next
End Sub

You should set a like this:
Dim a As Integer()
And then do a ReDim to initialise:
ReDim a(0 to ListBox1.Items.Count - 1)
Or however long you think a should be.

Related

How to add and convert text to double from a textbox to an array?

I am attempting to write code for a simple calculator that will store up to 10 results in an array.
I have the calculator portion working correctly but I am having troubles storing and displaying the results from the array.
Public Class wk2_David_Thieme_vb
Inherits System.Web.UI.Page
Dim resultArray(9) As Double
Dim i As Integer = 0
Protected Sub btnStore_Click(sender As Object, e As EventArgs) Handles btnStore.Click
Dim Num As Double
If i < 9 Then
For i = 0 To resultArray.Length - 1
Num = Convert.ToDouble(txtResult.Text)
resultArray(i) = Num
i += 1
Next i
Else
txtResult.Text = "10 results already stored"
End If
End Sub
Protected Sub btnDisplay_Click(sender As Object, e As EventArgs) Handles btnDisplay.Click
For i = 0 To UBound(resultArray)
lstResults.Items.Add(resultArray(i).ToString())
Next
End Sub
The results display 10 zeros in the listbox, no matter how what the user inputs into the calculator. Also, it doesn't display the "10 results already stored" once 10 entries have been added to the array. Thanks for any help you can provide, I am new to vb.net and am still learning, so please be gentle.
I make sample of using List ( of T) to store, display and clear :
Dim ListDoube As New List(Of Double)
Private Sub btnStore_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStore.Click
Dim Num As Double = 0
If ListDoube.Count < 10 Then
ListDoube.Add(If(Double.TryParse(txtResult.Text, Num), Num, 0))
Else
txtResult.Text = "10 results already stored"
End If
End Sub
Private Sub btnDisplay_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisplay.Click
For Each myVal In ListDoube
lstResults.Items.Add(myVal.ToString)
Next
End Sub
Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClear.Click
lstResults.Items.Clear()
End Sub
If you will still use array:
Dim resultArray(9) As Double
Dim i As Integer = 0
Private Sub btnStore_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStore.Click
Dim Num As Double = 0
If i < 10 Then
resultArray(i) = If(Double.TryParse(txtResult.Text, Num), Num, 0)
Else
txtResult.Text = "10 results already stored"
End If
i += 1
End Sub
Private Sub btnDisplay_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisplay.Click
For Each myVal In resultArray
lstResults.Items.Add(myVal.ToString)
Next
End Sub
Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClear.Click
For myCnt = 0 To 9
resultArray(myCnt) = 0
Next
lstResults.Items.Clear()
i = 0
txtResult.Text = ""
End Sub
I figured it out, mostly. The only issue now is that the results will always have a zero at the end of the list... not sure how to fix it. So if I input 2 entries, say 4+2 = 6 & 2+2 = 4, then the result array will have 6, 4, 0 in it. Any ideas how to fix this? Again, thanks for the support/help.
Public Shared resultArray(9) As Double
Public Shared i As Integer = 0
Protected Sub btnStore_Click(sender As Object, e As EventArgs) Handles btnStore.Click
If i >= 9 Then
lblError.Text = "10 results already stored"
Else
lblError.Text = ""
resultArray(i) = Convert.ToDouble(txtResult.Text)
If i < 9 Then
i += 1
End If
End If
End Sub
Protected Sub btnDisplay_Click(sender As Object, e As EventArgs) Handles btnDisplay.Click
If i <= 0 Then
lblError.Text = "You must add numbers"
Else
lstResults.Items.Clear()
lblError.Text = ""
For Num = 0 To i
lstResults.Items.Add(resultArray(Num))
Next Num
End If
End Sub
You don't need any For loop inside btnSave_Click. What a for loop does in your case is that it goes through all of items in your list and adds input number to your array. Instead you need to add each number separately to its own place in array.
To do that just change btnSave like below:
Dim doubleArray(9) As Double
Dim i As Integer = 0
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Dim Num As Double
If i < 10 Then
doubleArray(i) = (If(Double.TryParse(txtResult.Text, Num), Num, 0))
i += 1
Else
txtResult.Text = "10 results already stored"
End If
End Sub
That way there is nothing wrong inside your btnDisplay_Click.
You can instead use a List to save results in it. Therefore you've to declare a List(Of Double) instead of double array. So btnSave_Click should be changed as below:
Dim listOfDouble As New List(Of Double)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Num As Double
If listOfDouble.Count < 10 Then
listOfDouble.Add(If(Double.TryParse(txtResult.Text, Num), Num, 0))
Else
txtResult.Text = "10 results already stored"
End If
End Sub
And the you can iterate your list using For Each loop as:
Private Sub btnDisplay_Click(sender As Object, e As EventArgs) Handles btnDisplay.Click
For Each doubleVal In listOfDouble
listResults.Items.Add(doubleVal)
Next
End Sub

visual basic array sorting from list box

Hello im having trouble with my code !
we are asked to organize a list of names from a text.txt file the make them show up into a lits box (got that part down :) ) . then from the list box we are asked to create an array and sort that array (using our own sorting method) and organize the names using a button in assending order and another button organizing the array in decending order. the results from the orders names should appear in another list box .
i have gotten only the last name in the list to show up in the second list box but my code has no errors it just wont order the names properly! Help!!!!!
here is my code :)
Public Class FileSort
Dim sr As IO.StreamReader = IO.File.OpenText("C:\Users\Inspiron 15\documents\visual studio 2010\Projects\assigment4 EL\assigment4 EL\names.txt")
Structure names
Dim c As Integer
Dim fullname As String
End Structure
Dim allNames(99) As names
Private Sub btnName_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnName.Click
Do While sr.Peek <> -1
Name = sr.ReadLine
LstNames.Items.Add(Name & " ")
Loop
sr.Close()
End Sub
Private Sub bubbelsort(ByRef names() As System.String, ByVal c As Integer)
c = 0
names(c) = sr.ReadLine()
c = c * 1
For c = 1 To 99 Step +1 '~~~ Addding (Z to A) to the the Listbox
lstOrderedNames.Items.Add(Name & "")'
Next
End Sub
Private Sub BtnAssend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnAssend.Click
Dim names(99) As String
Dim c As Integer
c = 0
Dim A As Integer
A = 99
names(c) = sr.ToString
c = c + 1
For c = 1 To 99 Step +1 '~~~ Addding (Z to A) to the the Listbox
lstOrderedNames.Items.Add(Name & "")
Next
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnDessend.Click
Dim names(99) As String
Dim c As Integer
c = 0
Dim A As Integer
A = 99
names(c) = sr.ToString
names(A) = sr.ToString
A = A - 1
For A = 99 To 0 Step -1 '~~~ Addding (Z to A) to the the Listbox
lstOrderedNames.Items.Add(Name & "")
Next
End Sub
enter image description here
Since your problem is the sorting algorithm (if I understand this correctly).
At first we need an array.
Dim arr(ListBox1.Items.Count - 1) As String
For i As Integer = 0 To arr.Length - 1
arr(i) = CStr(ListBox1.Items(i))
Next
Next the sorting algorithm. Since you wanted to go with BubbleSort:
Private Sub StringBubbleSort(arr As String)
For i As Integer = 0 To arr.Length - 1
For j As Integer = 0 To arr.Length - 2 - i
If String.Compare(arr(j), arr(j + 1)) > 0 Then
Dim temp As String = arr(j)
arr(j) = arr(i)
arr(i) = temp
End If
Next
Next
End Sub
Then you use this function and copy the array to your second ListBox.
StringBubbleSort(arr)
ListBox2.Items.AddRange(arr)
String.Compare: https://msdn.microsoft.com/de-de/library/84787k22(v=vs.110).aspx
you could use linq
ListBox1.Items.Add("Battle")
ListBox1.Items.Add("Cattle")
ListBox1.Items.Add("apple")
ListBox2.DataSource = (From l In ListBox1.Items
Select l Order By l Ascending).ToList

vb.net option strict disallows late binding when trying to add to array cant turn off

I am trying to build my combobox with items from my array, but am getting this error:
Here is my code:
Private Sub frmInventory_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim InvArray As Array
InvArray = Inventory.BuildInvArray()
Option Strict Off
For i As Integer = 0 To 5
cmbSystem.Items.Add(InvArray(i,1))
Next
End Sub
It can be done by using Array.GetValue
Private Sub frmInventory_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim InvArray As Array
InvArray = Inventory.BuildInvArray()
For i As Integer = 0 To 5
cmbSystem.Items.Add(InvArray.GetValue(i, 1))
Next
End Sub

As sort an array of numbers in ascending order

I have a code to display a non-repeating random numbers, but I stuck by not sort in ascending order.
Here my code:
Public Class Form1
Dim intNumber As Integer
Dim arrNumber(0 To 5) As Integer
Dim i, x, y As Integer
Private Sub mostrar_resultados_sorteo(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
repetido()
For i = 0 To 5
ListBox1.Items.Add(arrNumber(i).ToString)
Next
End Sub
Private Sub repetido()
For x = 0 To 5
Start:
Randomize()
intNumber = Int((49 * Rnd()) + 1)
For y = 0 To 5
If intNumber = arrNumber(y) Then
GoTo Start
End If
Next y
arrNumber(x) = intNumber
Next x
ordenar()
End Sub
Private Sub ordenar()
End Sub
End Class
Your question is not tagged with programming language, but I guess it is VB.
Please see this link on how to sort an array.

NullReferenceException was unhandled VB.net Structure with Array

Public Class Form1
Structure Crap
Dim CrapA As Integer
Dim CrapB As Single
Dim CrapC() As Long
Private Sub Initialize()
ReDim CrapC(0 To 100)
End Sub
End Structure
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim Stuff(0 To 2) As Crap
Stuff(0).CrapA = 16
Stuff(1).CrapA = 32
Stuff(2).CrapA = 64
'This is the line where the NullReferenceException is thrown
Stuff(0).CrapC.Initialize()
For x = 0 To 100
Stuff(0).CrapC(x) = x ^ 2
Next x
MsgBox(Stuff(0).CrapA)
MsgBox(Stuff(1).CrapA)
MsgBox(Stuff(2).CrapA)
For x = 0 To 100
MsgBox(Stuff(0).CrapC(x))
Next x
End Sub
End Class
So this is a pretty simple program with a baffling error. All I want is an array in my user defined type. I'm moving from VB6 to .net and everything I've read, including What is a NullReferenceException, and how do I fix it? which is a hearty read, doesn't help. Seems I'm stuck in 1999, lol. I understand that the array CrapC is null, it's making it not null that's the problem.
The error happens here:
Stuff(0).CrapC.Initialize()
because the Crap() contains three instances of Crap but you never initialize the CrapC field which is a Long(). So you can call Initialize on Nothing(null). In most cases you don't need this method anyway: "This method is designed to help compilers support value-type arrays; most users do not need this method."
Instead use this array initializer to get a Long() with 100 longs:
Stuff(0).CrapC = New Long(99) {}

Resources