如何将 ListBox 控件的所有值传递给函数?

How to pass all value of ListBox Control to a function?

我正在编写一个简单的应用程序来读取文本框的值并将其添加到列表框控件中。但我必须将列表框控件传递给函数。有什么建议吗?

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    test("E:\Satyajit.txt")
End Sub

Public Function test(ByVal filename As String)
    Dim FILE_NAME As String = filename
    Dim TextLine As String
    Dim result As String = Path.GetFileName(FILE_NAME)
    Dim objReader As New System.IO.StreamReader(FILE_NAME)
    Do While objReader.Peek() <> -1
        TextLine = objReader.ReadLine()
        words = TextLine.Split(New Char() {","c})
        ListBox1.Items.Add(words(3) & "," & words(4))
        objItem = ListView1.Items.Add(words(3) & "," & words(4))
    Loop
  test1(ListBox1.Items)//pass the listbox value hare
End Function

Public Function test1(ByVal value As String)
    Dim Fest As String = value
    MsgBox(Fest)
End Function

您可以将整个控件传递给函数:

 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim lstbox As New ListBox
    lstbox.Items.Add("Hello")
    lstbox.Items.Add("Second Item")
    lstbox.Items.Add("Third Item")

    MsgBox("The list contains: " & Length(lstbox) & " characters")
End Sub

Function Length(ByVal ctrl As ListBox) As Integer
    Dim TotalNumberOfItems As Integer = 0
    For Each item As String In ctrl.Items.ToString
        TotalNumberOfItems += 1
    Next
    Return TotalNumberOfItems
End Function

或只是它的项目

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim lstbox As New ListBox
    lstbox.Items.Add("Hello")
    lstbox.Items.Add("Second Item")
    lstbox.Items.Add("Third Item")

    MsgBox("The list contains: " & Length(lstbox.Items) & " characters")
End Sub

Function Length(ByVal col As ListBox.ObjectCollection) As Integer
    Dim TotalNumberOfCharacters As Integer = 0
    For Each item As String In col
        TotalNumberOfCharacters += item.Length
    Next
    Return TotalNumberOfCharacters
End Function

您正在将 ListBox 的内容传递给一个方法,该方法只是在 MsgBox() 中显示它们。您可以采用两种方法来实现我认为您想要的。

  1. 您可以将 ListBox.Items 传递给方法并遍历每个项目,将它们连接成单个 StringStringBuilder,然后将字符串传递给 MsgBox()。这种方法使您的方法依赖于 ListBoxItems。

  2. 您可以遍历 ListBox.Items 将它们连接成一个 StringStringBuilder,然后将字符串传递给您的方法。这使您的方法更具可扩展性。

我推荐方法 #2,例如:

Dim MyListBox As New ListBox
MyListBox.Items.Add("Item1")
MyListBox.Items.Add("Item2")
MyListBox.Items.Add("Item3")
MyListBox.Items.Add("Item4")
MyListBox.Items.Add("Item5")

Dim sb As New StringBuilder
For Each Item In MyListBox.Items
    sb.AppendLine(Item)
Next
Test1(sb.ToString()) 

Test1 方法如下所示:

Public Sub Test1(ByVal value As String)
    MsgBox(value)
End Sub

结果: