Thanks alot.
On 24 June, 09:22, Cerebrus <[email protected]> wrote: > Two implementations - One non-generic and other Generic : (Hopefully, > someone can improve these... I'm famished right now! ;-) ) > > 1. Non-generic example: > ---------------------------------- > Private Shared Function getItem(ByVal oCol As ICollection, ByVal > sKey As String) As Object > Dim oItem As Object > Dim oItemVal As String = Nothing > Dim children As ICollection = Nothing > > For Each oItem In oCol > If TypeOf oCol Is MenuItemCollection Then > oItemVal = (CType(oItem, MenuItem)).Value > children = (CType(oItem, MenuItem)).ChildItems > ElseIf TypeOf oCol Is TreeNodeCollection Then > oItemVal = (CType(oItem, TreeNode)).Value > children = (CType(oItem, TreeNode)).ChildNodes > End If > > If oItemVal = sKey Then > Return oItem > ElseIf children.Count > 0 Then > Dim o As Object = getItem(children, sKey) > If o IsNot Nothing Then > Return o > End If > End If > Next > > Return Nothing > End Function > --- > > Invocation: > ----------- > Dim item1 As MenuItem = CType(getItem(menu1.Items, "SomeItem"), > MenuItem) > Dim item2 As TreeNode = CType(getItem(TV1.Nodes, "SomeNode"), > TreeNode) > > 2. Generic Example: > ------------------- > Private Shared Function GetAnyItem(Of T As ICollection, M)(ByVal > oCol As T, ByVal sKey As String) As M > Dim oItem As M > > For Each oItem In oCol > Dim mType As Type = oItem.GetType() > Dim valuePropertyName As String = Nothing > Dim childrenPropertyName As String = Nothing > > If TypeOf oCol Is MenuItemCollection Then > valuePropertyName = "Value" > childrenPropertyName = "ChildItems" > ElseIf TypeOf oCol Is TreeNodeCollection Then > valuePropertyName = "Value" > childrenPropertyName = "ChildNodes" > End If > > Dim oItemVal As String = Nothing > Dim children As T = Nothing > > Dim valPI As PropertyInfo = mType.GetProperty(valuePropertyName, > BindingFlags.Instance Or BindingFlags.Public Or > BindingFlags.DeclaredOnly) > oItemVal = valPI.GetValue(oItem, Nothing) > > Dim childPI As PropertyInfo = mType.GetProperty > (childrenPropertyName, BindingFlags.Instance Or BindingFlags.Public Or > BindingFlags.DeclaredOnly) > children = childPI.GetValue(oItem, Nothing) > > If oItemVal = sKey Then > Return oItem > ElseIf children.Count > 0 Then > Dim o As M = GetAnyItem(Of T, M)(children, sKey) > If o IsNot Nothing Then > Return o > End If > End If > Next > Return Nothing > > End Function > > Invocation: > ----------- > Dim item3 As MenuItem = GetAnyItem(Of MenuItemCollection, MenuItem) > (menu1.Items, "SomeItem") > Dim item4 As TreeNode = GetAnyItem(Of TreeNodeCollection, TreeNode) > (TV1.Nodes, "SomeNode")
