Friday, June 27, 2008

Using LINQ to Objects, Aggregate and Count() to get the count of a specific MDIChildren form type

This may not be the best way, but I thought it was a pretty cool way, so am sharing it.

Problem: I have a dynamic number instances of a specific form that are MDIChildren. There will be other kinds of MDIChildren forms as well. When the last, and only the last, instance of the specific form closes I want to do “something”.

Solution: Hook the FormClosed Event. In that event use Linq to Objects, Aggregate and Count() to get the current count of just that specific form type and if we’re closing the last form, do the “something.”

Hooking up the event when creating a new instance of the form in question (in the MDI Parent):

Dim ex As New ExampleForm
ex.MdiParent = Me
ex.Show()
AddHandler ex.FormClosed, AddressOf ExampleFormFormClosed

An instance of the given form closes, firing the FormClosed event (in the MDI Parent):

We’ll use Linq to Objects, filter by the form name and get the Count. if the count is 1, then we’re closing the last instance of that form

  Private Sub ExampleFormFormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs)
RemoveHandler DirectCast(sender, Form).FormClosed, AddressOf ExampleFormFormClosed

Dim EXForms As Integer = Aggregate a In Me.MdiChildren Where a.Name = "ExampleForm" Into Count()

If EXForms <= 1 Then 'When closing the last instance of the form, the count will still be 1
'Do the stuff you want to do when you close that last type of that MDIChild

End If

End Sub

Again, I’m a Linq noob, but I thought this pretty cool and wanted to capture it for the future… If there’s a better way, please feel free to comment. :)

No comments: