vb.net - 读取文件并输出到两个列表框
问题描述
我正在使用Imports System.IO
并StreamReader
在 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
我对阅读文件完全陌生。我真的不知道我在做什么。我对数组也很陌生。
谢谢!
解决方案
通过使用类,您可以创建包含颜色名称以及双精度值的对象并将它们添加到列表框中。
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
推荐阅读
- r - ggplot,根据采样时间的数据空间?
- python - 使用 tkinter 时,如何保存变量以供将来使用?
- amazon-web-services - 如何使用 aws-cdk python 设置 API 密钥
- laravel - 扩展和自定义 Laravel 重置密码逻辑
- python-3.x - 从 pdpbox 导入 pdp、get_dataset、info_plots 时出现 Python 错误
- sas - Proc sql如何使用生日提取大于18yrs的成员记录
- python - 从文件路径中提取“时间”
- javascript - 在字符串中格式化日期
- python - 如何将具有相等相邻条目的数组中的所有条目“归零”?
- r - R FlexDashboard 上的多个可视化(Leafletlet 和 Plotly)之间的交互性