2

Lots of examples of how to invoke methods, but how does one change a simple property?

For demonstration-sake, here's a very simple set of code that should help. Let's say I need to set the visible property from a child form, and thus, it needs to be invoked:

Friend Sub activateItem(ByVal myItem As PictureBox)

    If myItem.InvokeRequired = True Then
        ????
    Else
        myItem.Visible = True
    End If

End Sub

Thanks

Brad
  • 1,357
  • 5
  • 33
  • 65
  • Just invoke a method here, activateItem. Trying to optimize it is pointless, Invoke is *expensive*. – Hans Passant Oct 06 '10 at 02:59
  • Hans: when I invoke the method directly, I get an "Expression does not produce a value" error. After changing the sub to a function with Return True at the end, I get "Cannot cast binary to system.delegate" Any suggestions? I'm typically an asp.net guy, so dealing with threading is completely new to me. Thanks for the help. – Brad Oct 06 '10 at 12:13

1 Answers1

7

If you're using VB.Net 2010, you can use a lambda expression:

If myItem.InvokeRequired Then
    myItem.Invoke(Sub() myItem.Visible = True)

In your particular case, you can also call myItem.Invoke(myItem.Show).

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • Using VS2008 at the moment, so the first option isn't a choice. The second option gives me an error "myItem.Show does not produce a value" – Brad Oct 06 '10 at 12:05
  • Try `myItem.Invoke(AddressOf myItem.Show)` (I haven't done VB in a while) – SLaks Oct 06 '10 at 12:06
  • 1
    @Brad: Or try `myItem.Invoke(New Action(AddressOf myIem.Show))` – SLaks Oct 06 '10 at 12:30
  • New error there: AddressOf cannot be converted to System.Delegate because System.Delegate is declared MustInhereit and cannot be created. – Brad Oct 06 '10 at 12:32
  • I think our posts crossed in the mail. The second method worked. Thanks for your help! – Brad Oct 06 '10 at 12:33
  • Was hoping I would find someone who asked this question which had a good answer. +1 – Andez Jul 27 '12 at 21:44