當DataSource
屬性設置,您不能修改該列表。儘管使用DataSource
屬性填充ListBox
控件很方便,但它當然不是必需的。您可以使用其Items.Add
方法將項目添加到控件。舉例來說,從我的回答借用你剛纔的問題:
Public Class FileSearchTool
Public Sub New(ByVal listBox As ListBox, ByVal textBox As TextBox)
_listBox = listBox
_textBox = textBox
End Sub
Private _listBox As ListBox
Private WithEvents _textBox As TextBox
Private _fileNames As New List(Of String)()
Private _folderPath As String
Public Property FolderPath() As String
Get
Return _folderPath
End Get
Set(ByVal value As String)
_folderPath = value
loadFilePaths()
End Set
End Property
Private Sub loadFilePaths()
_fileNames = New List(Of String)(Directory.GetFiles(_folderPath))
refreshList()
End Sub
Private Sub _textBox_TextChanged(ByVal sender As Object, ByVal e As EventArgs) Handles _textBox.TextChanged
refreshList()
End Sub
Private Sub refreshList()
_listBox.SuspendLayout()
_listBox.Items.Clear()
For Each item As String In _fileNames
If item.StartsWith(_textBox.Text, StringComparison.CurrentCultureIgnoreCase) Then
_listBox.Items.Add(item)
End If
Next
_listBox.ResumeLayout()
End Sub
End Class
然後以任何形式,你可以使用這樣的:
Public Class Form1
Private _tool As FileSearchTool
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
_tool = New FileSearchTool(ListBox1, TextBox1)
_tool.FolderPath = "C:\"
End Sub
End Class
但是,在這一點上,你可能也只是將其封裝進一步通過創建一個FileSearch用戶控件。
或者,正如我在回答你剛纔的問題說,如果你想要的是一個自動完成框,你可以只使用文本框沒有一個列表框都這樣:
Dim source As New AutoCompleteStringCollection()
source.AddRange(Directory.GetFiles("C:\"))
TextBox1.AutoCompleteCustomSource = source
TextBox1.AutoCompleteMode = AutoCompleteMode.Suggest
TextBox1.AutoCompleteSource = AutoCompleteSource.CustomSource
在事實上,另一個有趣的選擇是,你可以設置AutoCompleteSource
到FileSystem
,你可能想玩。