July
13th,
2006
Several people have asked on the newsgroups about a good method to bind a list of items to entries in a ToolStripDropDown instance. I’ve run into this issue a couple of times and wanted to share some sample code.
The class takes in a ToolStripDropDown instance. You can then set the data source to any IEnumerable collection. Whenever the data in the list changes, call ReloadFromSource(). Or alternately, if the list implements IBindingList then it will automatically update.
Imports System.ComponentModel
Public Class DropDownBinding
Private m_dd As ToolStripDropDown
Private m_list As IEnumerable
Private m_bindingList As IBindingList
Public Sub New(ByVal dd As ToolStripDropDown)
m_dd = dd
m_list = New List(Of Object)()
End Sub
Public Sub SetDataSource(ByVal e As IEnumerable)
If Not m_bindingList Is Nothing Then
RemoveHandler m_bindingList.ListChanged, New ListChangedEventHandler(AddressOf Me.OnListChanged)
End If
m_bindingList = TryCast(e, IBindingList)
m_list = e
If Not m_bindingList Is Nothing Then
AddHandler m_bindingList.ListChanged, New ListChangedEventHandler(AddressOf Me.OnListChanged)
End If
RebuildList()
End Sub
Public Sub ReloadFromSource()
RebuildList()
End Sub
Private Sub OnListChanged(ByVal sender As Object, ByVal e As ListChangedEventArgs)
RebuildList()
End Sub
Private Sub RebuildList()
m_dd.Items.Clear()
For Each cur As Object In m_list
m_dd.Items.Add(cur.ToString())
Next
End Sub
End Class