2013-04-20 50 views
3

我有一个列表框,包含项目列表,我想知道如何创建一个处理程序,可以在事件发生时迭代ListBox。
我有以下代码将文件读取到列表框中。用事件监听器迭代ListBox的Visual Basic

Private Sub Load_File_To_ListBox(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Load_File_To_ListBox.Click 
    Dim r As New IO.StreamReader("C:\Users\resu\Desktop\test.txt") 
    While (r.Peek() > -1) 
     lb1.Items.Add(r.ReadLine) 
    End While 
    r.Close() 
End Sub 

这里是我的事件处理程序代码:

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click 
    TextBox1.Text = " " 
    TextBox1.Text &= ListBox1.SelectedItems.Item(i).ToString 
    i = i + 1 
End Sub 

i被声明为一个全局变量来跟踪的下一个项目的在ListBox。我想要的是从Listbox中读取下一个项目,并在Button2被单击时将其放入TextBox

请帮助我修改代码以使其正常工作。

回答

3

如果我理解正确的话,你的问题出在下面的代码行:

'This line of code looks at all of the items that have been 
'selected in the list box, and out of all of the selected 
'items it will select the item at index i. 
TextBox1.Text &= ListBox1.SelectedItems.Item(i).ToString 

因为代码是看选择的项目仅,而不是所有项目代码不像你期望的那样行事。而应使用以下代码行:

TextBox1.Text &= ListBox1.Items(i).ToString() 
+0

谢谢ByteBlast。 – devoidfeast 2013-04-20 10:46:35