Quick tricks

From HashVB
Revision as of 17:19, 15 February 2006 by Dee (Talk | contribs)

Jump to: navigation, search

There are HUNDREDS of quick (ugly :o) code hacks you can do in VB. Here are details of some:

Converting from CheckBox Values to a Boolean

Ever tried setting a CheckBox value straight from a boolean? I Used to use two functions for this that took one format and converted to the other using an if statement.

Function B2C(Value as Boolean) as Integer
  If Value Then
    B2C = 1
  Else
    B3C = 0
  End If
End Function

Function C2B(Value as Integer) as Boolean
  If Value = 1 Then
    B2C = True
  Else
    B3C = False
  End If
End Function

I then used IIf to shorten the function into a single inline statement.

CheckBox.Value = IIf(BooleanVariable, 1, 0)
BooleanVariable = (CheckBox.Value = 1)

I now use a much easier version that doesn't require branching. It does however rely on CheckBox values being 0 and 1 and Booleans to be 0 and -1 (Which should never change).

CheckBox.Value = -BooleanVariable
BooleanVariable = -CheckBox.Value

Checking the selected option button

This is a small hack I've used once or twice. It has no real advantage over a large If block, but I think it looks tidier.

Select Case True
Case Option(1): Msgbox "Option 1 is selected"
Case Option(2): Msgbox "Option 2 is selected"
Case Option(3): Msgbox "Option 3 is selected"
Case Option(4): Msgbox "Option 4 is selected"
End Select

This also works with CheckBoxes with the hack above if you want.

Enjoy :o)