首页 > 解决方案 > 读取文件并输出到两个列表框

问题描述

我正在使用Imports System.IOStreamReader在 Windows 窗体应用程序中。

我正在尝试获取一个文件,将其读入,然后将其输出到两个列表框中。文本文件的格式如下。

Blue, 23.7
Green, 60.1
Black, 45.3

我想将值高于 50 的颜色输出到一个列表框中,而将低于 50 的颜色输出到另一个列表框中。到目前为止,我所做的只是将整个列表输出到一个文本框中。代码如下所示:

srTextFile = File.OpenText(dataFile)

Do While srTextFile.EndOfStream = False
    'read file by line, use the comma as a splitter
    thisFile = srTextFile.ReadLine().Split(",")
    For i As Integer = 0 To thisFile.GetUpperBound(0)
        txtFileDisplay.AppendText(thisFile(i) &vbTab)
    Next
    txtFileDisplay.AppendText(vbCrLf)
Loop

我对阅读文件完全陌生。我真的不知道我在做什么。我对数组也很陌生。

谢谢!

标签: vb.netfile-io

解决方案


通过使用类,您可以创建包含颜色名称以及双精度值的对象并将它们添加到列表框中。

Public Class ColorValue
    Public Property Name As String
    Public Property Value As Double

    Public Overrides Function ToString() As String
        Return $"{Name} ({Value})"
    End Function
End Class

请注意,我已经覆盖了ToString,因为ListBox使用它来显示每个项目的文本。

现在,您可以像这样向列表框添加颜色

For Each line As String In File.ReadLines(dataFile)
    Dim parts As String() = line.Split(","c)
    If parts.Length = 2 Then 'If line is well-shaped.
        Dim value As Double
        Double.TryParse(Trim(parts(1)), value) 'Gets 0 into value if conversion fails.
        Dim color = New ColorValue With {.Name = parts(0), .Value = value}
        If value > 50.0 Then
            listBox1.Items.Add(color)
        Else
            listBox2.Items.Add(color)
        End If
    End If
Next

现在,您可以使用

Dim c As ColorValue = DirectCast(listBox1.SelectedItem, ColorValue)
Dim n As String = c.Name
Dim v As Double = c.Value

推荐阅读