我在Windows Forms应用程序中使用Imports System.IO
和StreamReader
。
我试图获取一个文件,读入它,并将其输出到两个列表框中。文本文件的格式如下。
Blue, 23.7
Green, 60.1
Black, 45.3
我想将值大于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
我对读取文件是完全陌生的。我真的不知道我在做什么。我对数组也很陌生。
谢谢!
答案 0 :(得分:0)
您可以利用System.IO.File
类来完成此操作
您可以这样编写代码:
For Each line As String In File.ReadAllLines("Your file here")
Dim Spl() AS String = Split(line, ",")
'Convert string value to integer
Dim myNum As Double = Double.Parse(Spl(1))'The number is the second item in the array
If myNum < 50.0 Then
'Add to your first Listbox here using
'Listbox.Add(myNum)
Else
'Add to your second Listbox here using
'Listbox.Add(myNum)
End If
Next
答案 1 :(得分:0)
通过使用类,您可以创建包含颜色名称和double值的对象,并将其添加到列表框中。
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