The "My" namespace in VB.NET is indispensable. Settings and resources among other things can be easily accessed by using it. You can place items such as files or images in "My.Resources" and access them in your code in a very simple manner:
Dim MyObject As Object MyObject = My.Resources.ObjectName
However, iterating through My.Resources is another issue. You might think you could do it this way:
For Each Object In My.Resources 'more code here Next
You can't. "My.Resources" is a namespace and not a collection that implements IEnumerable. So what do you do? You have to enumerate the objects in "My.Resources" if you want to iterate through them. I started out on the MSDN forums looking for a starting point and I came up with this implementation:
Public Function GetMyResourcesDictionary() As Dictionary(Of String, Object) Dim ItemDictionary As New Dictionary(Of String, Object) Dim ItemEnumerator As System.Collections.IDictionaryEnumerator Dim ItemResourceSet As Resources.ResourceSet Dim ResourceNameList As New List(Of String) ItemResourceSet = My.Resources.ResourceManager.GetResourceSet(New System.Globalization.CultureInfo("en"), True, True) 'Get the enumerator for My.Resources ItemEnumerator = ItemResourceSet.GetEnumerator Do While ItemEnumerator.MoveNext ResourceNameList.Add(ItemEnumerator.Key.ToString) Loop For Each resourceName As String In ResourceNameList ItemDictionary.Add(resourceName, GetItem(resourceName)) Next ResourceNameList = Nothing Return ItemDictionary End Function Public Function GetItem(ByVal resourceName As String) As Object Return My.Resources.ResourceManager.GetObject(resourceName) End Function
The reason I did it this way was so that I could call GetMyResourcesDictionary once and I'd have a Dictionary object that I could iterate through.
3 comments:
Great info!
Thanks so much.
Could you send me an example on how to actually iterate through the resources? As in the function call...I added your function to my class but can't get it to work. Help plz if you got time, thx.
aamir_raza60@hotmail.com
Thanks, I'm glad it helped! Aamir, I sent you an email.
Post a Comment