如何从Visual Basic中的列表框选择计算结果? (正在从文本文件中读取列表框中的数据)

时间:2016-06-29 10:08:13

标签: vb.net listbox project

所以我在学校要求创建一个铁路售票系统程序,允许您购买单程票或返程票,并根据该费用显示。所有目的地的信息都将通过文本文件读取。文本文件如下:

Knapford , 1
Crosby , 8
Weltworth , 15
Maron , 23
Cronk , 28
Kildane , 31
Keltthorpe Road , 46
Crovan's Gate , 56
Vicarstown , 76
Barrow , 77

我已设法通过下面的代码将整数与目标名称分开,然后显示在列表框中:

Public Class PurchaseScreen
Dim Filename As String
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Filename = "StationFile.txt"
    Dim sr As New StreamReader("StationFile.txt")
    Dim Word As String = ""
    Dim Words(11) As String
    Dim i As Integer = 0

    Do Until sr.Peek = -1

        'grab one word at a time from the text file
        Word = sr.ReadLine()

        'place word into array
        Words(i) = Word

        'increment array counter
        i = i + 1

    Loop

    Return
End Sub

我面临的问题是我正在尝试访问代码省略的数字,因为只有目标名称可以显示在列表框中。如何使用这些数字进行计算?

1 个答案:

答案 0 :(得分:0)

我已对您的帖子进行了编辑,以便阅读问题的用户更清楚文本文件的格式

因此,为了更容易访问您的数据,您最好使用Station结构并将每个工作站存储在这些结构的列表中。

要填充列表,请遍历站列表并将名称添加到列表中。

选择某个项目后,使用所选项目的索引在站点列表中查找数据,然后就可以了。

'obviously you need to change this path to match where your "stations.txt"file is stored
'and also possibly the name of the listbox you're populating
Dim Filename As String = "D:\Visual Studio 2015\Projects\blank\blank\stations.text"
Dim selectedStation As Station

'a structure of station that can be used to store the data in the stations.txt file
'in a clearer more maintainable way
Structure Station
    Dim Name As String
    Dim Data As Single
End Structure

'list to store the data from stations.txt
Dim stations As New List(Of Station)

'your form's load event
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    stations.Clear()
    ReadStationData()
    PopulateListBox()
End Sub

Private Sub ReadStationData()
    Dim tempDataLine As String = ""
    'read all the stations.txt data into a string
    Using sr As New StreamReader(Filename)
        While Not sr.EndOfStream
            tempDataLine = sr.ReadLine
            Dim newStation As Station
            Dim tempSplit() As String = tempDataLine.Split(New String() {" , "}, StringSplitOptions.RemoveEmptyEntries)
            newStation.Name = tempSplit(0)
            newStation.Data = CSng(tempSplit(1))
            stations.Add(newStation)
        End While
    End Using
End Sub

'clear the ListBox and populate it from the Stations list
Private Sub PopulateListBox()
    ListBox1.Items.Clear()
    For Each stationItem As Station In stations
        ListBox1.Items.Add(stationItem.Name)
    Next
End Sub

Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
    'dummy code to show usage
    selectedStation = stations(ListBox1.SelectedIndex())
    MessageBox.Show("Selected station = " & selectedStation.Name & vbCrLf & "Station price = " & selectedStation.Data)
End Sub