【问题标题】:For Each Item in ListBox1 do something then add item to listbox2 vb对于 ListBox1 中的每个项目做一些事情,然后将项目添加到 listbox2 vb
【发布时间】:2013-11-01 00:50:48
【问题描述】:

我制作了一个应用程序来将某些数字转换为其他格式
即

  • 1 = 一个
  • 2 = B
  • 3 = C
  • 4 = D
  • 5 = E
  • 等

我已经毫无问题地制作了该功能,并且我已经使用了很长时间,但现在我想更快地批量处理。
所以我真的很难从文本文件复制到我的 Textbox1 然后按 button1 然后将 textbox2 复制到其他文本文件。

所以我正在考虑将文本文件加载到列表框中,然后将该列表中的每个项目循环到第二个列表中,我可以将其导出到另一个文本文件。

我已经介绍了导入和导出,但我坚持的地方是制作循环。

如果您知道更好的方法,请告诉我或告诉我如何解决此问题。

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Using FD As New OpenFileDialog()
        FD.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
        If FD.ShowDialog = Windows.Forms.DialogResult.OK Then
            ListBox1.Items.Clear()
            ListBox1.Items.AddRange(IO.File.ReadAllLines(FD.FileName))
        End If
    End Using
End Sub


Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    Do
    Dim Item As String = ""
    For Each i As String In ListBox1.Items
        Item &= i
        TextBox1.Text = Item
        TextBox2.Text = MYFUNCTION(TextBox1.Text)
        ListBox2.Items.Add(TextBox2.Text)
        TextBox1.Text = ""
        TextBox2.Text = ""
    Next
    Loop Until TextBox1.Text = "END"

End Sub

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
    'TextBox2.Text = MeidHexToDec(TextBox1.Text)

    Using FD As New SaveFileDialog()
        FD.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
        If FD.ShowDialog = Windows.Forms.DialogResult.OK Then
            Dim FileContent As String = ""
            For Each i As String In ListBox2.Items
                FileContent &= i & vbCrLf
            Next
            IO.File.WriteAllText(FD.FileName, FileContent)
        End If
    End Using
End Sub

所以我的最终目标是做这样的事情:

TextFile1.txt

  • 1
  • 2
  • 5
  • 5
  • 1
  • 3
  • 2
  • 结束

然后转换后输出

文本文件2.txt

  • 一个
  • B
  • E
  • E
  • 一个
  • C
  • 乙

文本文件的大小有时会有所不同,有时只有 10 个项目,有时会是 50... 谢谢。

【问题讨论】:

    标签: vb.net loops foreach listboxitems


    【解决方案1】:

    您根本不需要Do 循环,您可以简化其余的循环逻辑,如下所示:

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        For Each i As String In ListBox1.Items
            ListBox2.Items.Add(MYFUNCTION(i))
        Next
    End Sub
    

    您不需要注意END 标记,因为文件中的所有内容都被读入ListBox1.Items 集合,因此一旦您遍历了ListBox1.Items 中的所有字符串值,那么您就是在文件末尾。

    MYFUNCTION 逻辑返回从数字到字母的转换,因此只需将该函数的结果添加到ListBox2.Items 中即可。

    【讨论】:

      【解决方案2】:
      Public Function Letr(N As Int16) As String
          Letr = Chr(N + 64)
      End Function
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-10
        • 2019-12-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多