所以我有一个带有菜单栏和lstbox的表单。在菜单栏上是显示选项,有3个选项;所有,小说或非小说。文本文件按顺序包含书名,作者,类别(fic或nonfic),股票,价格。当用户点击全部显示时,我希望所有标题都显示在列表框中。如果他们点击Nonfic,只点击非文字标题,与小说相同。到目前为止,这是我的代码:
Private Sub menuDisplay_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles menuDisplay.Click
Dim books() As String = IO.File.ReadAllLines("Books.txt")
Dim data() As String
Dim allBooksTitle, allNonFicTitle, allFicTitle As String
For i As Integer = 0 To books.Count - 1
data = books(i).Split(","c)
allBooksTitle = data(2)
If data(2).Trim = "N" Then
allNonFicTitle = data(0)
ElseIf data(2).Trim = "F" Then
allFicTitle = data(0)
End If
Next
' show result
If menuDisplayAll.Checked Then
lstBox.Items.Add(allBooksTitle)
ElseIf menuDisplayFic.Checked Then
lstBox.Items.Add(allFicTitle)
ElseIf menuDisplayNonFic.Checked Then
lstBox.Items.Add(allNonFicTitle)
End If
End Sub
我不太确定如何编写要显示的小说或非小说书籍标题的代码,以及列表框在每个按钮之间刷新而不是添加到列表框。任何帮助都非常适用!
答案 0 :(得分:0)
在此代码中显示数据的最佳方法是将显示代码移动到处理循环中。
Private Sub menuDisplay_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles menuDisplay.Click
Dim books() As String = IO.File.ReadAllLines("Books.txt")
lstbox.Items.Clear() 'remove all items from the listbox
For i As Integer = 0 To books.Count - 1
Dim data() As String 'Moved inside to limit scope
Dim allBooksTitle, allNonFicTitle As String
data = books(i).Split(","c)
allBooksTitle = data(2) 'store the two fields
allNonFicTitle = data(0)
If menuDisplayAll.Checked Then 'check for each item
lstBox.Items.Add(allBooksTitle)
ElseIf menuDisplayFic.Checked AndAlso data(2).Trim = "F" Then
lstBox.Items.Add(allNonFicTitle)
ElseIf menuDisplayNonFic.Checked AndAlso data(2).Trim = "N"Then
lstBox.Items.Add(allNonFicTitle)
End If
Next
End Sub
但是,如果使用.net 3.5或更高版本,则使用LINQ
可能更清晰Private Sub menuDisplay_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles menuDisplay.Click
Dim books() As String = IO.File.ReadAllLines("Books.txt")
lstbox.Items.Clear()
Dim query As IEnumerable(Of String)
If menuDisplayAll.Checked Then 'check for each item
query = From book As String In books let data As String() = book.Split(',') Select data(0)
ElseIf menuDisplayFic.Checked
query = From book As String In books let data As String() = book.Split(',') Where data(2).Trim = "F" Select data(2)
ElseIf menuDisplayNonFic.Checked
query = From book As String In books let data As String() = book.Split(',') Where data(2).Trim = "N" Select data(2)
End If
lstBox.Items.AddRange(query)
End Sub