1

The button's width is 123. Why doesn't the following change it's width

Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
    With Me.Button3
        IIf(.Width = 123, .Width = 233, .Width = 150)
    End With
End Sub

Does IIF just return a value? i.e if I want to set the button's width property then do I need to use an If structure?

Very little said about Iif in MSDN

whytheq
  • 34,466
  • 65
  • 172
  • 267

3 Answers3

2

Your code tests .Width = 123, then returns the boolean expression .Width = 233 if true or .Width = 150 if false, then throws the result away. This is not what you intended. You have three alternatives:

' IIf function - not recommended since it is not typesafe and evaluates all arguments.
.Width = IIf(.Width = 123, 233, 150)

' If operator - typesafe and only evaluates arguments as necessary.
.Width = If(.Width = 123, 233, 150)

' If statement - not an expression.
If .Width = 123 Then .Width = 233 Else .Width = 150
Christian Hayter
  • 30,581
  • 6
  • 72
  • 99
2

Use VB.NEt's If()-statement. It's called 'conditional operator' and exists in many languages. IIf is a VB-specific function and has a different behaviour. More information here: Performance difference between IIf() and If

In both cases, IIf and If just return a value (the IIF ones isn't typed; it's an object that has to be casted). It seems to do the thing you want anyway:

Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
    Button3.Width = If(Button3.Width = 123, 233, 150)
End Sub
Community
  • 1
  • 1
nikeee
  • 10,248
  • 7
  • 40
  • 66
1

Does IIF just return a value?

Yes.

i.e if I want to set the button's width property then do I need to use an If structure?

No, because you can assign the return value to the Width property:

With Me.Button3 
    .Width = IIf(.Width = 123, 233, 150) 
End With 

Note that, in current versions of VB.NET, the If Operator should be used instead of Iif, since it has a variety of advantages (type safety, short-circuiting, etc.). For example, using If(...) would allow your code to compile without an additional cast even if you had Option Strict On (which you should).

With Me.Button3 
    .Width = If(.Width = 123, 233, 150) 
End With 
Heinzi
  • 167,459
  • 57
  • 363
  • 519
  • ok - I'm assuming that VB's `Option Strict On` is equivalent functionality to VBA's `Option Explicit` ? – whytheq Sep 27 '12 at 07:29
  • @whytheq: No, VB's `Option Explicit` is equivalent to VBA's `Option Explicit`. [`Option Strict` is something new:](http://msdn.microsoft.com/de-de/library/vstudio/zcd4xwzs.aspx) It disallows implicit conversions. – Heinzi Sep 27 '12 at 07:41