Recent changes Random page
GAMING
Technology
 
Gaming
Entertainment
Science Fiction
Biggest wikis
Hobbies
Music
See more...

Write Shorter VB Code

From Visual Basic Wiki

Jump to: navigation, search

Contents

[edit] Description

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

[edit] Make a button disable if a text box is empty

[edit] Long Way

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

[edit] Short Way

Command.Enabled = TextBox.Text <> ""

[edit] 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.

[edit] 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.

[edit] 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

[edit] Short Way

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

[edit] What it means

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

Rate this article:
Share this article:
.