我正在编写一个简单的应用程序来读取文本框的值并添加到列表框控件中。但我必须将列表框控件传递给函数。有什么建议吗?
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
答案 0 :(得分:1)
您正在将ListBox
的内容传递给仅在MsgBox()
中显示的方法。你可以采取两种方法来完成我认为你想要的东西。
您可以将ListBox.Items
传递给该方法并迭代每个项目,将它们连接成一个String
或StringBuilder
,然后将字符串传递给MsgBox()
。此方法使您的方法依赖于ListBoxItems。
您可以迭代ListBox.Items
将它们连接成一个String
或StringBuilder
,然后将String传递给您的方法。这使您的方法更具可扩展性。
我推荐方法#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
结果:
答案 1 :(得分:0)
您可以将整个控件传递给函数:
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