putting a list into an array?

情到浓时终转凉″ 提交于 2019-12-11 10:00:21

问题


Firstly, I just want to say I'm a beginner in vb.net and just coding in general. If possible, our professor probably intended for us to use the simplest method possible So please don't suggest fancy and abstract methods for doing what I'm trying to do. Thank you :)

So I have a listbox. There's no set number of items. I can enter as many numbers as I want And I want to convert all the items in that listbox into an array But obviously, you can't see an array. So I made it so that it prints itself out in a label. But only the last number inputted into the listbox came out.

My code for getting the listbox into an array is this:

Dim i As Integer

For i = 0 To lstbxInput.Items.Count
    dblarray(i) = CDbl(lstbxInput.Items(i))
Next i

And in this sub, dblarray as double was used as a reference parameter.

And to print out the array, I used this code:

Dim DblArray(lstbxInput.Items.Count - 1) As Double

getNumbers(DblArray)
lblLrgAns.Text = DblArray(lstbxInput.Items.Count - 1).ToString

I don't fully understand Byref and hopefully I used it the right way. I used dimmed the dblarray there because that's what the professor told us to do.


回答1:


Based on your code below, you have got the array (DblArray) exactly what you wanted

Dim DblArray(lstbxInput.Items.Count - 1) As Double

getNumbers(DblArray)

Now regarding your problem:

But only the last number inputted into the listbox came out.

That's because of this syntax

lblLrgAns.Text = DblArray(lstbxInput.Items.Count - 1).ToString

You only take the last item of DblArray, which is DblArray(lstbxInput.Items.Count - 1). What you need to get is DblArray(0) (the first item), DblArray(1) (the second item), DblArray(2) (the third item), ... , up until DblArray(lstbxInput.Items.Count - 1) (the last item). Assuming you want to assign all of DblArray items to lblLrgAns.Text separated by comma, you'll need a loop like below

Dim i As Integer

For i = 0 To DblArray.Length - 1
    lblLrgAns.Text = lblLrgAns.Text & DblArray(i).ToString

    ' add a comma unless it's the last index
    If (i < DblArray.Length - 1)
        lblLrgAns.Text = lblLrgAns.Text & ", "
    End If
Next i


来源:https://stackoverflow.com/questions/27229131/putting-a-list-into-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!