我正在开发一个程序,用户必须从列表框中选择项目(lstCommercial)并保存到访问文件,问题是只有最后选择的项目显示在访问文件中,这里是我的代码
Public Class Form1
Dim outfile As IO.StreamWriter
Dim infile As IO.StreamReader
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
lstCommercial.Items.Add("Cheerios")
lstCommercial.Items.Add("Doritos")
lstCommercial.Items.Add("T-mobile")
lstCommercial.Items.Add("Radioshack")
End Sub
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
' open the file to create
outfile = IO.File.CreateText("commercial.txt")
' write the name on a separate line in the file
outfile.WriteLine(lstCommercial.SelectedItems)
' close the file
lstCommercial.Focus()
outfile.Close()
End Sub
Private Sub btnDisplay_Click(sender As Object, e As EventArgs) Handles btnDisplay.Click
End Sub
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Me.Close()
End Sub
End Class
答案 0 :(得分:1)
而不是:
' write the name on a separate line in the file
outfile.WriteLine(lstCommercial.SelectedItems)
...试试这个:
' write the name on a separate line in the file
For Each item In lstCommercial.SelectedItems
outfile.WriteLine(item)
Next
问题在于您没有迭代SelectedItems集合中的所有元素。另外,请确保将lstCommercial
ListBox的SelectionMode属性设置为MultiSimple或MultiExtended,并确保在点击btnSave
时实际选择了多个项目。