XTab's Blog

Ged Mead's Blog at vbCity

This blog hosted by:
http://blogs.vbcity.com      
  Home :: Syndication  :: Login

SepOctober 2006Nov
SMTWTFS
24252627282930
1234567
891011121314
15161718192021
22232425262728
2930311234

Archives

Topics

Ramblings

VB.NET

Tuesday, October 31, 2006 #

   In these blogs I mostly try to point up new (and hopefully improved) features that you can get in Visual Studio 2005 or VB 2005 that weren't available in earlier versions.    In many cases, of course, it was quite possible to do something in say VB.NET 2003 -  it just wasn't always the easiest job in the world to get there.

   And keeping track of the forms that are open in a WinForms project is a good example.  I'll run through the pre-2005 version first, but if you've landed on this blog item because you want the VB 2005 answer and aren't interested in the fascinating but (for you ) useless technical tramp through the VB.NET 2003 way , then just scroll down to the very bottom and there it will be.

   If you have need of a VB.NET 2003 approach though (or just want to be impressed with how much 2003 code can be dispensed with by using 2005) then here's a pre-2005 way of creating your own collection of forms and tracking them.  


Module FormsCollection
    Public Forms As New FormsCollectionClass
End Module

Class FormsCollectionClass : Implements IEnumerable

Public AllForms As New Collection

Sub Add(ByVal f As Form)
    AllForms.Add(f)
End Sub


Sub Remove(ByVal f As Form)
   Dim itemCount As Integer
   For itemCount = 1 To AllForms.Count
     If f Is AllForms.Item(itemCount) Then
       AllForms.Remove(itemCount)
       Exit For
     End If

ReadOnly Property Item(ByVal index As Integer) As Form
     Get
       Return DirectCast(AllForms.Item(index), Form)
     End Get
End Property

Overridable Function GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator
     Return AllForms.GetEnumerator
End Function

End Class


   After creating the above code, you still need a mechanism for each individual form to add or remove itself from the collection.   This in the Sub New of each form:

Forms.Add(Me)

and this in the Dispose procedure:

Forms.Remove(Me)

  Once all that is in place, you can access the collection as it dynamically grows and reduces.  Maybe you want to display the names of the currently open forms in a listbox:

ListBox1.Items.Clear()
For Each frm As Form In Forms
 ListBox1.Items.Add(frm.Name)
Next

   So that seems to be the VB.NET 2003 way (I always wondered if there was a shorter approach using the FindWindow API, but never did get round to really investigating that possibility.)   Relatively long-winded, but achievable.   Now compare that to:



>>> The VB 2005 Way  <<<

ListBox1.Items.Clear()
For Each frm As Form In My.Application.OpenForms
  ListBox1.Items.Add(frm.Name)
Next



      Four lines of code vs. maybe thirty-four.   Could it be any easier?   Now that's what I call an upgrade!

posted @ 8:30 PM