プロパティが設定されている場合DataSource
、リストを変更することはできません。ListBox
プロパティを使用してコントロールに入力すると便利DataSource
ですが、必須ではありません。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
実際、もう 1 つの興味深いオプションは、 に設定できるAutoCompleteSource
ことFileSystem
です。