Difference between revisions of "Quick tricks"

From HashVB
Jump to: navigation, search
(Ugly hacks part 1)
 
(Part 2, Select Case hacks)
Line 1: Line 1:
 
There are HUNDREDS of quick (ugly :o) code hacks you can do in VB. Here are details of some:
 
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 ===
+
== Converting from CheckBox Values to a Boolean ==
 
Ever tried setting a CheckBox value straight from 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.
 
I Used to use two functions for this that took one format and converted to the other using an if statement.
Line 30: Line 30:
 
  CheckBox.Value = -BooleanVariable
 
  CheckBox.Value = -BooleanVariable
 
  BooleanVariable = -CheckBox.Value
 
  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)
 
Enjoy :o)

Revision as of 17:19, 15 February 2006

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)