vb

Description

This tutorial will show you how to make smaller code to save time.

Make a button disable if a text box is empty

Long Way

If TextBox.Text = "" Then
    Command.Enabled = False
Else
    Command.Enabled = True
End If

Short Way

Command.Enabled = TextBox.Text <> ""

What it means

The long way shows the command button being disabled if the textbox is empty or enabled if it has data in it.

The short way uses simple expressions to achieve the effect in one line. The expression TextBox.Text <> "" means that if the TextBox contains data it returns true and if it doesn't it returns false. Change the enabled to visible if you want to make it invisible instead.

Use IIf

Note of warning: use IIf only when the expressions to be returned are constants; otherwise you will get a performance penalty. If the arguments to IIf are functions or expressions, they will be evaluated, which is especially important to remember if your functions have side effects, a long running time, or if this particular IIf is called a lot, for instance in a loop.

Long Way

Dim RealData, ThisData As Boolean
ThisData = True
If ThisData Then
    RealData = "This data is true"
Else
    RealData = "This data is false"
End If
MsgBox RealData

Short Way

Dim ThisData As Boolean, RealData
ThisData = True
RealData = IIf(ThisData, "This data is true", "This data is false")
MsgBox RealData

What it means

IIf is a function that is used instead of the usual C style "expr ? truePart : falsePart"