1

I'm trying to clean up my coding practices, and came across this I could not solve.

With option strict on, how you you find an instance of a form and run a public sub on said instance?

For example in an inventory package, i have a shortcut to checkout a part, which finds if a check out form is open and runs Checkout.AddID(ID as Integer). EG:

For Each Form In Application.OpenForms
    If Form.Name = "FRMCheckout" Then
        Form.AddIDToList(PartID)
    End If
Next

This works fine with option strict off. However, turn it on and modify it to suit such as:

For Each Form As Windows.Forms.Form In Application.OpenForms
    ' If Form.Name = "FRMCheckout" Then EDIT: Dropped this in leu of this:
    If TypeOf (Form) Is FRMCheckout Then
        Form.AddIDToList(Ctype(PartID, Integer))
    End If
Next
     

Throws the error (obviously) that .AddIDToList is not a member of Forms.form.

Changing to For Each Form as ProgramNamespace.FRMCheckout would throw 'Cannot cast type form to FRMcheckout' when ever the for loop hits a normal form.

What would be a way to accomplish this without turning off option strict?

Nimantha
  • 6,405
  • 6
  • 28
  • 69
Josh
  • 89
  • 12
  • DirectCast(Form, FRMCheckout).AddIDToList(Ctype(PartID, Integer). Do consider what will happen the user opened *two* instances of FRMCheckout. Always best to not have to figure it out at the last possible moment, use the constructor to tell the FRMCheckout class with what object it should co-operate. – Hans Passant Jul 09 '16 at 09:34

2 Answers2

3

Look for OfType enumerable extension, the code is just

For Each checkout In Application.OpenForms.OfType(Of FRMCheckout)()
    checkout.AddIDToList(Ctype(PartID, Integer))
Next

Now the loop returns only the forms of type FRMCheckout and the iterator variable is already strongly typed so you could call its public methods and properties without any conversion. Of course all the grunt work is done inside the OfType extension so it is not really an improvement in performance if any is expected but just a more clear way to write and understand a piece of code

Steve
  • 213,761
  • 22
  • 232
  • 286
  • I love it when a way to do the same thing that took 5 lines, now takes 1 :) thanks. (EDIT: Thanks for the link) – Josh Jul 09 '16 at 09:28
  • Yes, this extension is really neat and probably one of the most used. It works very well also to find a set of controls on your form (_Form.Controls.OfType(Of TextBox)_ for example) – Steve Jul 09 '16 at 09:31
2

So I found the following is a solution, and looks a little neater in my opinion:

Option Strict On

For Each Form As Windows.Forms.Form In Application.OpenForms
   If TypeOf (Form) Is FRMCheckout Then
        Dim Checkout_Instance As FRMCheckout = CType(Form, FRMCheckout)
        Checkout_Instance.AddIDToList(PartID.ToString)
   End If
Next

This works.

Josh
  • 89
  • 12