简体   繁体   English

选择数组vb中的特定项目

[英]Select a specific item in a array vb

I have the text file with year numbers and a line return then another number. 我有一个文本文件,其中包含年份数字和一行返回,然后是另一个数字。

Year 1991
8
Year 1990
14

An array carries the year number and another one carries the number below it. 一个数组带有年份数字,另一个带有年份数字。

strYear(intCount) = objReader.ReadLine()
dblSum(intCount) = Convert.ToDouble(objReader.ReadLine())

The user selects the year from a combo box and I have it outputted I just don't know how to output the apparent number from the year selected. 用户从组合框中选择年份,然后输出它,我只是不知道如何从所选年份中输出表观数字。

You can use the SelectedIndex of the ComboBox as an index into the array. 您可以将ComboBoxSelectedIndex用作数组的索引。

Dim sum = dblSum(myComboBox.SelectedIndex)

That said, instead of doing it that way, why not add both values to one object, put those objects in a list and then bind that list to the ComboBox . 就是说,不是那样做,为什么不将两个值都添加到一个对象,将这些对象放在列表中,然后将该列表绑定到ComboBox You could then get the sum value directly from the SelectedValue property of the ComboBox . 然后,您可以直接从ComboBoxSelectedValue属性获取总和值。 Eg 例如

Dim items As New List(Of Tuple(Of String, Double))

'...

items.Add(Tuple.Create(objReader.ReadLine(), Convert.ToDouble(objReader.ReadLine()))

'...

With myComboBox
    .DisplayMember = "Item1"
    .ValueMember = "Item2"
    .DataSource = items
End With

'...

Dim sum = CDbl(myComboBox.SelectedValue)

It's convenient to use Tuples here but you can use a class or structure of your own if you prefer. 在这里使用Tuples很方便,但是如果愿意,可以使用自己的类或结构。

As you're reading alternate lines from your text file into two arrays (years first, numbers second) the index into the second array of numbers should be the same as the index into the first array of years. 当您从文本文件中将备用行读取到两个数组(年份,第二个数字)中时,第二个数字数组中的索引应与第一个年份数组中的索引相同。

If the first array of years is used to directly populate your combobox, then the selected index of the combo will also be the index into the array of numbers for the number associated with the selected year. 如果使用第一个年份数组直接填充您的组合框,则该组合的所选索引也将是与所选年份相关联的数字数组的索引。

So dblSum(myComboBox.SelectedIndex) would give you the correct number. 因此, dblSum(myComboBox.SelectedIndex)将为您提供正确的数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM