首页 > 解决方案 > 从文本文件中每隔四行读取一次

问题描述

所以,我有一个包含以下内容的文本文件:

Andrew Law
0276376352
13 Parsons St
Kevin Kyle
0376458374
29 Penrod Drive
Billy Madison
06756355
16 Stafford Street

现在在我的表单上,我有一个 ListBox。当表单加载时,我想从文本文件(每个名称)中每隔四行读取一次并将其显示在 ListBox 中。

我现在只有以下内容:

Dim People As String
People = System.IO.File.ReadAllLines("filelocation")(3)
ListBox1.Items.Add(People)

但是,这仅读取第 4 行,因为我也想在此之后读取每第四行。

标签: vb.netwinformslistbox

解决方案


当当前行是要跳过的预定义行数的倍数时,将从源文件中提取的所有字符串添加0到 ListBox 或 , 并允许用户从列表中选择名称以使用详细信息填充一些标签与所选名称相关。

  • 从字符串数组中解析并提取人名。每个名称都可以在一个索引处找到,该索引是skipLines字段指定值的倍数。
  • 将每个名称添加到 ListBox 控件。
  • 从名称列表框列表中选择名称时,将相关详细信息添加到某些标签(已命名lblPhoneNumberlblAddress此处)。为了识别数组中的正确信息,这次我们使用该skipLines值作为乘数。这样,即使您在名称列表中添加更多详细信息,您也会找到仅修改skipLines值的正确信息。
    您需要订阅 ListBox 的SelectedIndexChanged事件:

Public Class Form1
    Private people As String()
    Private skipLines As Integer = 0

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        skipLines = 3
        people = File.ReadAllLines([Source File])
        For line As Integer = 0 To people.Length - 1
            If line Mod skipLines = 0 Then
                ListBox1.Items.Add(people(line))
            End If
        Next
    End Sub

    Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
        Dim StartIndex As Integer = ListBox1.SelectedIndex * skipLines
        lblPhoneNumber.Text = people(StartIndex + 1)
        lblAddress.Text = people(StartIndex + 2)
    End Sub
End Class

这是如何工作的

定义要跳过的行数。我们想要一行文本,然后跳过 3 行,这里:

Dim skipLines As Integer = 3

我们创建一个字符串数组。它将包含File.ReadAllLines()的输出,它当然会返回一个字符串数组:

Dim people As String() = File.ReadAllLines([Source File])

逐行迭代字符串数组的全部内容。集合枚举从 开始0,因此我们将列表从 解析0为元素数- 1

For line As Integer = 0 To people.Length - 1
'[...]
Next

当前If行号是 的倍数时满足条件skipLinesMod 运算符将两个数字相除并返回运算的余数
。如果没有提醒,数字是我们要跳过的行数的倍数。lineskipLines

If line Mod skipLines = 0 Then
`[...]
End If

最后,当满足条件时,将people当前line值表示的索引处的字符串数组(数组)的内容添加到ListBox.Items集合中:

ListBox1.Items.Add(people(line))

推荐阅读