Powerscript Ref1 PDF
Powerscript Ref1 PDF
Volume 1
PowerBuilder
8
DOCUMENT ID: 37781-01-0800-01
To order additional documents, U.S. and Canadian customers should call Customer Fulfillment at (800) 685-8225, fax (617) 229-9845.
Customers in other countries with a U.S. license agreement may contact Customer Fulfillment via the above fax number. All other
international customers should contact their Sybase subsidiary or local distributor. Upgrades are provided only at regularly scheduled
software release dates. No part of this publication may be reproduced, transmitted, or translated in any form or by any means, electronic,
mechanical, manual, optical, or otherwise, without the prior written permission of Sybase, Inc.
Sybase, the Sybase logo, ADA Workbench, Adaptable Windowing Environment, Adaptive Component Architecture, Adaptive Server,
Adaptive Server Anywhere, Adaptive Server Enterprise, Adaptive Server Enterprise Monitor, Adaptive Server Enterprise Replication,
Adaptive Server Everywhere, Adaptive Server IQ, Adaptive Warehouse, AnswerBase, Anywhere Studio, Application Manager,
AppModeler, APT Workbench, APT-Build, APT-Edit, APT-Execute, APT-FORMS, APT-Translator, APT-Library, Backup Server,
ClearConnect, Client-Library, Client Services, Data Pipeline, Data Workbench, DataArchitect, Database Analyzer, DataExpress,
DataServer, DataWindow, DB-Library, dbQueue, Developers Workbench, Direct Connect Anywhere, DirectConnect, Distribution
Director, E-Anywhere, E-Whatever, Embedded SQL, EMS, Enterprise Application Studio, Enterprise Client/Server, Enterprise Connect,
Enterprise Data Studio, Enterprise Manager, Enterprise SQL Server Manager, Enterprise Work Architecture, Enterprise Work Designer,
Enterprise Work Modeler, EWA, Financial Fusion, Financial Fusion Server, Gateway Manager, ImpactNow, InfoMaker, Information
Anywhere, Information Everywhere, InformationConnect, InternetBuilder, iScript, Jaguar CTS, jConnect for JDBC, KnowledgeBase,
MainframeConnect, Maintenance Express, MAP, MDI Access Server, MDI Database Gateway, media.splash, MetaWorks, MySupport,
Net-Gateway, Net-Library, ObjectConnect, ObjectCycle, OmniConnect, OmniSQL Access Module, OmniSQL Toolkit, Open Client,
Open ClientConnect, Open Client/Server, Open Client/Server Interfaces, Open Gateway, Open Server, Open ServerConnect, Open
Solutions, Optima++, PB-Gen, PC APT Execute, PC DB-Net, PC Net Library, Power++, power.stop, PowerAMC, PowerBuilder,
PowerBuilder Foundation Class Library, PowerDesigner, PowerDimensions, PowerDynamo, PowerJ, PowerScript, PowerSite,
PowerSocket, Powersoft, PowerStage, PowerStudio, PowerTips, Powersoft Portfolio, Powersoft Professional, PowerWare Desktop,
PowerWare Enterprise, ProcessAnalyst, Report Workbench, Report-Execute, Replication Agent, Replication Driver, Replication Server,
Replication Server Manager, Replication Toolkit, Resource Manager, RW-DisplayLib, RW-Library, S-Designor, SDF, Secure SQL
Server, Secure SQL Toolset, Security Guardian, SKILS, smart.partners, smart.parts, smart.script, SQL Advantage, SQL Anywhere, SQL
Anywhere Studio, SQL Code Checker, SQL Debug, SQL Edit, SQL Edit/TPU, SQL Everywhere, SQL Modeler, SQL Remote, SQL
Server, SQL Server Manager, SQL SMART, SQL Toolset, SQL Server/CFT, SQL Server/DBM, SQL Server SNMP SubAgent, SQL
Station, SQLJ, STEP, SupportNow, Sybase Central, Sybase Client/Server Interfaces, Sybase Financial Server, Sybase Gateways, Sybase
MPP, Sybase SQL Desktop, Sybase SQL Lifecycle, Sybase SQL Workgroup, Sybase User Workbench, SybaseWare, Syber Financial,
SyberAssist, SyBooks, System 10, System 11, System XI (logo), SystemTools, Tabular Data Stream, Transact-SQL, Translation Toolkit,
UNIBOM, Unilib, Uninull, Unisep, Unistring, URK Runtime Kit for UniCode, Viewer, Visual Components, VisualSpeller, VisualWriter,
VQL, WarehouseArchitect, Warehouse Control Center, Warehouse Studio, Warehouse WORKS, Watcom, Watcom SQL, Watcom SQL
Server, Web Deployment Kit, Web.PB, Web.SQL, WebSights, WebViewer, WorkGroup SQL Server, XA-Library, XA-Server and XP
Server are trademarks of Sybase, Inc. 3/01
Unicode and the Unicode Logo are registered trademarks of Unicode, Inc.
All other company and product names used herein may be trademarks or registered trademarks of their respective companies.
Use, duplication, or disclosure by the government is subject to the restrictions set forth in subparagraph (c)(1)(ii) of DFARS 52.227-
7013 for the DOD and as set forth in FAR 52.227-19(a)-(d) for civilian agencies.
VOLUME 1
C H APTE R 3 Declarations................................................................................... 35
Declaring variables......................................................................... 36
Where to declare variables...................................................... 36
iii
Contents
iv
Contents
v
Contents
UPDATE....................................................................................... 174
UPDATEBLOB ............................................................................. 175
UPDATE Where Current of Cursor .............................................. 177
Using dynamic SQL ..................................................................... 178
Dynamic SQL Format 1................................................................ 182
Dynamic SQL Format 2................................................................ 183
Dynamic SQL Format 3................................................................ 185
Dynamic SQL Format 4................................................................ 188
vi
Contents
ItemChanged................................................................................ 259
ItemChanging............................................................................... 260
ItemCollapsed .............................................................................. 261
ItemCollapsing ............................................................................. 262
ItemExpanded .............................................................................. 263
ItemExpanding ............................................................................. 264
ItemPopulate ................................................................................ 265
Key ............................................................................................... 266
LineDown ..................................................................................... 268
LineLeft ........................................................................................ 269
LineRight ...................................................................................... 270
LineUp.......................................................................................... 271
LoseFocus.................................................................................... 272
Modified........................................................................................ 274
MouseDown ................................................................................. 276
MouseMove.................................................................................. 279
MouseUp...................................................................................... 283
Moved .......................................................................................... 286
Open ............................................................................................ 287
Other ............................................................................................ 290
PageDown.................................................................................... 291
PageLeft....................................................................................... 292
PageRight .................................................................................... 293
PageUp ........................................................................................ 294
PictureSelected ............................................................................ 295
PipeEnd........................................................................................ 296
PipeMeter..................................................................................... 297
PipeStart ...................................................................................... 298
PrintFooter ................................................................................... 299
PrintHeader .................................................................................. 300
PropertyChanged ......................................................................... 301
PropertyRequestEdit .................................................................... 302
RButtonDown ............................................................................... 303
RButtonUp.................................................................................... 305
RemoteExec................................................................................. 306
RemoteHotLinkStart ..................................................................... 307
RemoteHotLinkStop ..................................................................... 308
RemoteRequest ........................................................................... 309
RemoteSend ................................................................................ 310
Rename........................................................................................ 311
Resize .......................................................................................... 312
RightClicked ................................................................................. 313
RightDoubleClicked...................................................................... 316
Save ............................................................................................. 318
vii
Contents
SaveObject................................................................................... 319
Selected ....................................................................................... 320
SelectionChanged ........................................................................ 321
SelectionChanging ....................................................................... 324
Show ............................................................................................ 326
Sort............................................................................................... 327
SystemError ................................................................................. 330
SystemKey ................................................................................... 331
Timer ............................................................................................ 332
ToolbarMoved .............................................................................. 334
ViewChange................................................................................. 335
VOLUME 2
viii
Contents
ix
Contents
x
Contents
Fill................................................................................................. 510
Find .............................................................................................. 511
FindCategory................................................................................ 513
FindClassDefinition ...................................................................... 515
FindFunctionDefinition ................................................................. 516
FindItem ....................................................................................... 517
FindMatchingFunction .................................................................. 523
FindNext....................................................................................... 525
FindSeries .................................................................................... 526
FindTypeDefinition ....................................................................... 527
FromAnsi...................................................................................... 529
FromUnicode................................................................................ 530
GarbageCollect ............................................................................ 532
GarbageCollectGetTimeLimit ....................................................... 533
GarbageCollectSetTimeLimit ....................................................... 534
GetActiveSheet ............................................................................ 535
GetAlignment ............................................................................... 536
GetApplication.............................................................................. 537
GetArgElement............................................................................. 538
GetAutomationNativePointer........................................................ 539
GetCertificateLabel ...................................................................... 541
GetChildrenList ............................................................................ 544
GetColumn ................................................................................... 546
GetCommandDDE ....................................................................... 548
GetCommandDDEOrigin.............................................................. 550
GetCompanyName ...................................................................... 551
GetContextKeywords ................................................................... 552
GetContextService ....................................................................... 553
GetCredentialAttribute.................................................................. 555
GetCurrentDirectory ..................................................................... 558
GetData........................................................................................ 559
GetDataDDE ................................................................................ 564
GetDataDDEOrigin....................................................................... 565
GetDataPieExplode...................................................................... 566
GetDataStyle................................................................................ 568
GetDataValue............................................................................... 574
GetDynamicDate.......................................................................... 576
GetDynamicDateTime .................................................................. 578
GetDynamicNumber..................................................................... 580
GetDynamicString ........................................................................ 581
GetDynamicTime ......................................................................... 582
GetEnvironment ........................................................................... 583
GetFileOpenName ....................................................................... 584
GetFileSaveName........................................................................ 586
xi
Contents
xii
Contents
xiii
Contents
xiv
Contents
xv
Contents
PrintBitmap................................................................................... 901
PrintCancel................................................................................... 902
PrintClose..................................................................................... 904
PrintDataWindow ......................................................................... 905
PrintDefineFont ............................................................................ 906
PrintGetPrinter ............................................................................. 908
PrintGetPrinters............................................................................ 909
PrintLine ....................................................................................... 910
PrintOpen ..................................................................................... 912
PrintOval ...................................................................................... 914
PrintPage ..................................................................................... 916
PrintRect ...................................................................................... 917
PrintRoundRect ............................................................................ 919
PrintScreen .................................................................................. 921
PrintSend ..................................................................................... 922
PrintSetFont ................................................................................. 924
PrintSetPrinter.............................................................................. 925
PrintSetSpacing ........................................................................... 926
PrintSetup .................................................................................... 927
PrintSetupPrinter.......................................................................... 928
PrintText....................................................................................... 929
PrintWidth..................................................................................... 931
PrintX ........................................................................................... 932
PrintY ........................................................................................... 933
ProfileInt ....................................................................................... 934
ProfileString.................................................................................. 936
Rand............................................................................................. 938
Randomize ................................................................................... 939
Read............................................................................................. 940
Real.............................................................................................. 943
RegistryDelete.............................................................................. 944
RegistryGet .................................................................................. 945
RegistryKeys ................................................................................ 947
RegistrySet................................................................................... 948
RegistryValues ............................................................................. 950
RelativeDate................................................................................. 951
RelativeTime ................................................................................ 952
ReleaseAutomationNativePointer ................................................ 953
ReleaseNativePointer .................................................................. 954
RemoteStopConnection ............................................................... 955
RemoteStopListening ................................................................... 956
RemoveDirectory ......................................................................... 957
Repair........................................................................................... 958
Replace ........................................................................................ 959
xvi
Contents
xvii
Contents
xviii
Contents
xix
Contents
xx
About This Book
Subject This book describes syntax and usage information for the PowerScript
language, including variables, expressions, statements, events, and
functions.
Audience This book is for programmers who will be using PowerBuilder to build
client/server, multitier, and Web applications.
Two volumes The printed version of this book is divided into two volumes:
Volume Contents
Volume 1 Chapters 1-9
Volume 2 Chapter 10 (PowerScript Functions)
xxi
PART 1 PowerScript Topics
CH A PTE R 1 Language Basics
About this chapter This chapter describes general elements and conventions of PowerScript.
Contents
Topic Page
Comments 4
Identifier names 6
Labels 8
Special ASCII characters 9
NULL values 11
Reserved words 13
Pronouns 14
Statement continuation 18
Statement separation 20
White space 21
3
Comments
Comments
Description You can use comments to document your scripts and prevent statements within
a script from executing. There are two methods.
Syntax Double-slash method
Code // Comment
Slash-and-asterisk method
/* Comment */
Usage Here is how to use each method:
Method Marker Can use to Note
Double // Designate all text on the line Cannot extend to multiple
slash to the right of the marker as a lines
comment
Slash and /*...*/ Designate the text between Can extend over multiple
asterisk the markers as a comment lines (multiline comments do
Nest comments not require a continuation
character)
Can be nested
For information about adding comments to objects and library entries, see the
PowerBuilder User’s Guide.
Examples Double-slash method
// This entire line is a comment.
// This entire line is another comment.
4
Chapter 1 Language Basics
Slash-and-asterisk method
/* This is a single-line comment. */
5
Identifier names
Identifier names
Description You use identifiers to name variables, labels, functions, windows, controls,
menus, and anything else you refer to in scripts.
Syntax Rules for identifiers:
• Must start with a letter or an _ (underscore)
• Cannot be reserved words (see "Reserved words" on page 13)
• Can have up to 40 characters but no spaces
• Are case insensitive (PART, Part, and part are identical)
• Can include any combination of letters, numbers, and these special
characters:
- Dash
_ Underscore
$ Dollar sign
# Number sign
% Percent sign
Usage By default, PowerBuilder allows you to use dashes in all identifiers, including
in variable names in a script. This means that when you use the subtraction
operator or the -- operator in a script, you must surround it with spaces. If you
do not, PowerBuilder interprets the expression as an identifier name.
If you want to disallow dashes in variable names in scripts, you can change the
setting of the Allow Dashes in Identifiers option in the script editor’s property
sheet. This way you do not have to surround the subtraction operator and the
decrement assignment shortcut (--) with spaces.
Be careful
If you disallow dashes and have previously used dashes in variable names, you
will get errors the next time you compile.
6
Chapter 1 Language Basics
Invalid identifiers
2nd-quantity // Does not start with a letter
ABC Code // Contains a space
Child’sId // Contains invalid special character
7
Labels
Labels
Description You can include labels in scripts for use with GOTO statements.
Syntax Identifier :
Usage A label can be any valid identifier. You can enter it on a line by itself above the
statement or at the start of the line before the statement.
For information about the GOTO statement, see GOTO on page 141. For
information about valid identifiers, see "Identifier names" on page 6.
Examples On a line by itself above the statement
FindCity:
IF city=cityname[1] THEN ...
At the start of the line before the statement
FindCity: IF city=cityname[1] THEN ...
8
Chapter 1 Language Basics
Examples Entering ASCII characters Here is how to use special characters in strings:
String Description
"dog~n" A string containing the word dog followed by a newline
character
"dog~tcat~ttiger" A string containing the word dog, a tab character, the word cat,
another tab character, and the word tiger
9
Special ASCII characters
10
Chapter 1 Language Basics
NULL values
Description NULL means undefined or unknown. It is not the same as an empty string or
zero or a date of 0000-00-00. For example, NULL is neither 0 nor not 0.
Typically, you work with NULL values only with respect to database values.
Usage Initial values for variables Although PowerBuilder supports NULL values
for all variable data types, it does not initialize variables to NULL. Instead,
when a variable is not set to a specific value when it is declared, PowerBuilder
sets it to the default initial value for the data type—for example, zero for a
numeric value, FALSE for boolean, and the empty string ("") for a string.
NULL variables A variable can become NULL if one of the following
occurs:
• A NULL value is read into it from the database. If your database supports
NULL, and a SQL INSERT or UPDATE statement sends a NULL to the
database, it is written to the database as NULL and can be read into a
variable by a SELECT or FETCH statement.
NULL in a variable
When a NULL value is read into a variable, the variable remains NULL
unless it is changed in a script.
11
NULL values
Examples Example 1 None of the following statements make the computer beep (the
variable nbr is set to NULL, so each statement evaluates to NOT TRUE):
int Nbr
// Set Nbr to NULL.
SetNull(Nbr)
IF Nbr =1 THEN Beep(1)
IF Nbr <> 1 THEN Beep(1)
IF NOT (Nbr = 1) THEN Beep(1)
Example 2 In this IF...THEN statement, the boolean expression evaluates to
NOT TRUE, so the ELSE is executed:
int a
SetNull(a)
IF a = 1 THEN
MessageBox("Value", "a = 1")
ELSE
MessageBox("Value", "a = NULL")
END IF
Example 3 This example is a more useful application of a NULL boolean
expression than Example 2. It displays a message if no control has focus. When
no control has focus, GetFocus returns a NULL object reference, the boolean
expression evaluates to NOT TRUE, and the ELSE is executed:
IF GetFocus( ) THEN
. . . // Some processing
ELSE
MessageBox("Important", "Specify an option!")
END IF
12
Chapter 1 Language Basics
Reserved words
The words PowerBuilder uses internally are called reserved words and cannot
be used as identifiers. If you use a reserved word as an identifier, you get a
compiler warning. Reserved words that are marked with an asterisk (*) can be
used as function names.
alias event not static
and* execute of step
autoinstantiate exit on subroutine
call external open* super
case false or system
catch fetch parent systemread
choose finally post* systemwrite
close* first prepare then
commit for prior this
connect forward private throw
constant from privateread throws
continue function privatewrite to
create* global procedure trigger
cursor goto protected true
declare halt protectedread try
delete if protectedwrite type
describe* immediate prototypes until
descriptor indirect public update*
destroy insert readonly updateblob
disconnect into ref using
do intrinsic return variables
dynamic is rollback while
else last rpcfunc with
elseif library select within
end loop selectblob _debug
enumerated next shared
The PowerBuilder system class also includes private variables that cannot be
used as identifiers. If you use a private variable as an identifier, you get an
informational message and should rename your identifier.
13
Pronouns
Pronouns
Description PowerScript has pronouns that allow you to make a general reference to an
object or control. When you use a pronoun, the reference remains correct even
if the name of the object or control changes.
Syntax These are the pronouns:
• Parent pronoun
• This pronoun
• Super pronoun
Usage You can use pronouns in function and event scripts wherever you would use an
object’s name. For example, you can use a pronoun to:
• Cause an event in an object or control
• Manipulate or change an object or control
• Obtain or change the setting of a property
The individual pronouns Each pronoun has a specific meaning and use:
14
Chapter 1 Language Basics
Parent pronoun
Description Parent in a PowerBuilder script refers to the object that contains the current
object.
Usage You can use the pronoun Parent in scripts for:
• Controls in windows
• Custom user objects
• Menus
Where you use Parent determines what it references:
Window controls When you use Parent in a script for a control (such as a
CommandButton), Parent refers to the window that contains the control.
User object controls When you use Parent in a script for a control in a
custom user object, Parent refers to the user object.
Menus When you use Parent in a menu script, Parent refers to the menu item
on the level above the menu the script is for.
Examples Window controls If you include this statement in the script for the Clicked
event in a CommandButton within a window, clicking the button closes the
window containing the button:
Close(Parent)
If you include this statement in the script for the CommandButton, clicking the
button displays a horizontal scrollbar within the window (sets the HScrollBar
property of the window to TRUE):
Parent.HScrollBar = TRUE
User object controls If you include this statement in a script for the Clicked
event for a CheckBox in a user object, clicking the checkbox hides the user
object:
Parent.Hide( )
If you include this statement in the script for the CheckBox, clicking the
checkbox disables the user object (sets the Enabled property of the user object
to FALSE):
Parent.Enabled = FALSE
Menus If you include this statement in the script for the Clicked event in the
menu item Select All under the menu item Select, clicking Select All disables
the menu item Select:
Parent.Disable( )
15
Pronouns
If you include this statement in the script for the Clicked event in the menu item
Select All, clicking Select All checks the menu item Select:
Parent.Checked = TRUE
This pronoun
Description The pronoun This in a PowerBuilder script refers to the window, user object,
menu, application object, or control that owns the current script.
Usage Why include This Using This allows you to make ownership explicit. This
statement refers to the current object’s X property:
This.X = This.X + 50
When optional but helpful In the script for an object or control, you can
refer to the properties of the object or control without qualification. But it is
good programming practice to include This to make the script clear and easy to
read.
When required There are some circumstances when you must use This.
When a global or local variable has the same name as an instance variable,
PowerBuilder finds the global or local variable first. Qualifying the variable
with This allows you to refer to the instance variable instead of the global
variable.
EAServer restriction
You cannot use This to pass arguments in EAServer components.
Examples Example 1 This statement in a script for a menu places a checkmark next to
the menu selection:
This.Check( )
Example 2 In this function call, This passes a reference to the object
containing the script:
ReCalc(This)
Example 3 If you omit This, x in the following statement refers to a local
variable x if there is one defined (the script adds 50 to the variable x, not to the
X property of the control). But it refers to the object’s X property if there is no
local variable:
x = x + 50
16
Chapter 1 Language Basics
Example 4 Use This to ensure that you refer to the property. For example, the
following statement in the script for the Clicked event for a CommandButton
means that clicking the button changes the horizontal position of the button
(changes the button’s X property):
This.x = This.x + 50
Super pronoun
Description When you write a PowerBuilder script for a descendant object or control, you
can call scripts written for any ancestor. You can directly name the ancestor in
the call, or you can use the reserved word Super to refer to the immediate
ancestor.
Usage Whether to use Super If you are calling an ancestor function, you only need
to use Super if the descendant has a function with the same name and the same
arguments as the ancestor function. Otherwise, you would simply call the
function with no qualifiers.
Restrictions for Super You cannot use Super to call scripts associated with
controls in the ancestor window. You can only use Super in an event or function
associated with a direct descendant of the ancestor whose function is being
called. Otherwise, the compiler returns a syntax error.
To call scripts associated with controls, use the CALL statement.
See the discussion of CALL on page 127.
Examples Example 1 This example calls the ancestor function wf_myfunc (presumably
the descendant also has a function called wf_myfunc):
Super::wf_myfunc(myarg1, myarg2)
This example has to be part of a script or function in the descendent window,
not one of the window’s controls. For example, if it is in the Clicked event of
a button on the descendent window, you get a syntax error when the script is
compiled.
Supplying arguments
Be certain to supply the correct number of arguments for the ancestor function.
17
Statement continuation
Statement continuation
Description Although you typically put one statement on each line, you occasionally need
to continue a statement to more than one line. The statement continuation
character is the ampersand (&).
Syntax Start of statement &
more statement &
end of statement
The ampersand must be the last nonwhite character on the line (or the compiler
considers it part of the statement).
For information about white space, see "White space" on page 21.
Usage You do not use a continuation character for:
• Continuing comments Do not use a continuation character to continue
a comment. The continuation character is considered part of the comment
and is ignored by the compiler.
• Continuing SQL statements You do not need a continuation character
to continue a SQL statement. In PowerBuilder, SQL statements always
end with a semicolon (;), and the compiler considers everything from the
start of a SQL statement to a semicolon to be part of the SQL statement. A
continuation character in a SQL statement is considered part of the
statement and usually causes an error.
Examples Continuing a quoted string
One way You can continue a quoted string by simply placing an ampersand
in the middle of the string and continuing the string on the next line:
IF Employee_District = "Eastern United States and&
Eastern Canada" THEN ...
Note that any white space (such as tabs and spaces) before the ampersand and
at the beginning of the continued line is part of the string.
A problem This statement uses only the ampersand to continue the quoted
string in the IF...THEN statement to another line; for readability, a tab has been
added to indent the second line. The compiler includes the tab in the string,
which may result in an error:
IF Employee_District = "Eastern United States and&
Eastern Canada" THEN ...
18
Chapter 1 Language Basics
19
Statement separation
Statement separation
Description Although you typically put one statement on each line, you occasionally want
to combine multiple statements on a single line. The statement separation
character is the semicolon (;).
Syntax Statement1; statement2
Examples The following line contains three short statements:
A = B + C; D = E + F; Count = Count + 1
20
Chapter 1 Language Basics
White space
Description Blanks, tabs, formfeeds, and comments are forms of white space. The compiler
treats white space as a delimiter and does not consider the number of white
space characters.
Usage White space in string literals The number of white space characters is
preserved when they are part of a string literal (enclosed in single or double
quotation marks).
Dashes in identifiers Unless you have prohibited the use of dashes in
identifiers (see "Identifier names" on page 6), you must surround a dash used
as a minus sign with spaces. Otherwise, PowerBuilder considers the dash part
of a variable name:
Order - Balance // Subtracts Balance from Order
Order-Balance // A variable named Order-Balance
Examples Example 1 Here the spaces and the comment are white space, so the compiler
ignores them:
A + B /*Adjustment factor */+C
Example 2 Here the spaces are within a string literal, so the compiler does
not ignore them:
"The value of A + B is:"
21
White space
22
CH A PTE R 2 Data Types
About this chapter This chapter describes the PowerScript data types.
Contents
Topic Page
Standard data types 24
Any data type 29
System object data types 32
Enumerated data types 33
PowerBuilder data types in EAServer 34
23
Standard data types
Blob Binary large object. Used to store an unbounded amount of data (for example,
generic binary, image, or large text such as a word-processing document).
Boolean Contains TRUE or FALSE.
Char or character A single ASCII character.
If you have character-based data that you will want to parse in an application,
you might want to define it as an array of type char. Parsing a char array is
easier and faster than parsing strings. If you will be passing character-based
data to external functions, you may want to use char arrays instead of strings.
For more information about passing character-based data to external functions,
see Application Techniques. For information about data type conversion when
assigning strings to chars and vice versa, see "String and char data types in
PowerBuilder" on page 78.
Using literals To assign a literal value, enclose the character in either single
or double quotation marks. For example:
char c
c = ’T’
c = "T"
Date The date, including the full year (1000 to 3000), the number of the month (01
to 12), and the day (01 to 31).
Using literals To assign a literal value, separate the year, month, and day
with hyphens. For example:
1992-12-25 // December 25, 1992
24
Chapter 2 Data Types
25
Standard data types
Real A signed floating-point number with six digits of precision and a range from
1.175495E-38 to 3.402822E+38.
Using literals To assign a literal value, use a decimal value, followed by E,
followed by an integer; no spaces are allowed. The decimal number before the
E follows all the conventions specified above for decimal literals. The leading
plus sign in the exponent (the integer following the E) is optional (3E5 and
3E+5 are the same). For example:
2E4 2.5E78 +6.02E3 -4.1E-2
-7.45E16 7.7E+8 3.2E-45
String Any ASCII character with variable length (0 to 2,147,483,647).
Most of the character-based data in your application, such as names, addresses,
and so on, will be defined as strings. PowerScript provides many functions that
you can use to manipulate strings, such as a function to convert characters in a
string to uppercase and functions to remove leading and trailing blanks.
For more information about passing character-based data to external functions,
see Application Techniques. For information about data type conversion when
assigning strings to chars and vice versa, see "String and char data types in
PowerBuilder" on page 78.
Using literals To assign a literal value, enclose as many as 1024 characters
in either single or double quotes, including a string of zero length or an empty
string. For example:
string s1
s1 = ’This is a string’
s1 = "This is a string"
You can embed a quotation mark in a string literal if you enclose the literal with
the other quotation mark. For example:
string s1
s1 = "Here’s a string."
results in the string Here’s a string.
You can also use a tilde (~) to embed a quotation mark in a string literal. For
example:
string s1 = ’He said, "It~’s good!"’
Complex nesting When you nest a string within a string that is nested in
another string, you can use tildes to tell the parser how to interpret the quotation
marks. Each pass through the parser strips away the outermost quotes and
interprets the character after each tilde as a literal. Two tildes become one tilde,
and tilde-quote becomes the quote alone.
26
Chapter 2 Data Types
27
Standard data types
• Pairs of single quotes ( ' ) can be used in place of pairs of tilde double
quotes (~")
• Pairs of tilde tilde single quotes (~~’) can be used in place of pairs of triple
tilde double quotes (~~~")
Time The time in 24-hour format, including the hour (00 to 23), minute (00 to 59),
second (00 to 59), and fraction of second (up to six digits), with a range from
00:00:00 to 23:59:59:999999.
PowerBuilder supports microseconds in the database interface for any DBMS
that supports microseconds.
Using literals The time in 24-hour format, including the hour (00 to 23),
minute (00 to 59), second (00 to 59), and fraction of second (up to six digits),
with a range from 00:00:00 to 23:59:59.999999. You separate parts of the time
with colons—except for fractional sections, which should be separated by a
decimal point. For example:
21:09:15 // 15 seconds after 9:09 pm
06:00:00 // Exactly 6 am
10:29:59 // 1 second before 10:30 am
10:29:59.9 // 1/10 sec before 10:30 am
UnsignedInteger, 16-bit unsigned integers, from 0 to 65,535.
UnsignedInt, or UInt
UnsignedLong or 32-bit unsigned integers, from 0 to 4,294,967,295.
ULong
28
Chapter 2 Data Types
Declarations and You declare Any variables just as you do any other variable.
assignments
You assign data to Any variables with standard assignment statements. You can
assign an array to a simple Any variable. You can also declare an array of Any
variables, where each element of the array can have a different data type.
After you assign a value to an Any variable, you can test the variable with the
ClassName function and find out the actual data type:
any la_spreadsheetdata
la_spreadsheetdata = ole_1.Object.cells(1,1).value
CHOOSE CASE ClassName(la_spreadsheetdata)
CASE "integer"
...
CASE "string"
...
END CHOOSE
These rules apply to Any assignments:
• You can assign anything into an Any variable.
• You must know the content of an Any variable to make assignments from
the Any variable to a compatible data type.
Restrictions If the value of a simple Any variable is an array, you can’t access the elements
of the array until you assign the value to an array variable of the appropriate
data type. This restriction does not apply to the opposite case of an array of Any
variables—you can access each Any variable in the array.
29
Any data type
If the value of an Any variable is a structure, you can’t use dot notation to
access the elements of the structure until you assign the value to a structure of
the appropriate data type.
After a value has been assigned to an Any variable, it can’t be converted back
to a generic Any variable without a data type. Even if you set it to NULL, it
retains the data type of the assigned value until you assign another value.
Operations and You can perform operations on Any variables as long as the data type of the
expressions data in the Any variable is appropriate to the operator. If the data type isn’t
appropriate to the operator, an execution error occurs.
For example, if instance variables ia_1 and ia_2 contain numeric data, this
statement is valid:
any la_3
la_3 = ia_1 - ia_2
If ia_1 and ia_2 contain strings, you can use the concatenation operator:
any la_3
la_3 = ia_1 + ia_2
However, if ia_1 contained a number and ia_2 contained a string, you would
get an execution error.
Data type conversion functions PowerScript data type conversion
functions accept Any variables as arguments. When you call the function, the
Any variable must contain data that can be converted to the specified type.
For example, if ia_any contains a string, you can assign it to a string variable:
ls_string = ia_any
If ia_any contains a number that you want to convert to a string, you can call
the String function:
ls_string = String(ia_any)
Other functions If a function’s prototype does not allow Any as a data type
for an argument, you cannot use an Any variable without a conversion
function, even if it contains a value of the correct data type. When you compile
the script, you will get compiler errors such as Unknown function or Function
not found.
For example, the argument for the Len function refers to a string column in a
DataWindow, but the expression itself has a type of Any:
IF Len(dw_notes.Object.Notes[1]) > 0 THEN // Invalid
30
Chapter 2 Data Types
This will work because the string value of the Any expression is explicitly
converted to a string:
IF Len(String(dw_notes.Object.Notes[1])) > 0 THEN
Expressions whose data type is Any Expressions that access data whose
type is unknown when the script is compiled have a data type of Any. These
expressions include expressions or functions that access data in an OLE object
or a DataWindow object:
myoleobject.application.cells(1,1).value
dw_1.Object.Data[1,1]
dw_1.Object.Data.empid[99]
The objects these expressions point to can change so that the type of data being
accessed changes too.
Expressions that refer to DataWindow data can return arrays and structures and
arrays of structures as Any variables. For best performance, you should assign
the DataWindow expression to the appropriate array or structure without using
an intermediate Any variable.
Overusing the Any Do not use Any variables as a substitute for selecting the correct data type in
data type your scripts. There are two reasons for this:
• At execution time, using Any variables is slow PowerBuilder must
do much more processing to determine data types before it can make an
assignment or perform an operation involving Any variables. In particular,
an operation performed many times in a loop will suffer greatly if you use
Any variables instead of variables of the appropriate type.
• At compile time, using Any variables removes a layer of error
checking from your programming The PowerBuilder compiler makes
sure data types are correct before code gets executed. With Any variables,
errors that can be caught by the compiler are not found until the code is
run.
31
System object data types
32
Chapter 2 Data Types
Incorrect syntax
Do not enclose an enumerated data type value in quotation marks or you will
receive a compiler error.
Advantages of Enumerated data types have the following advantage over standard data types:
enumerated types when an enumerated data type is required, the compiler checks the data and
makes sure it is the correct type. For example, if you set an enumerated data
type variable to any other data type or to an incorrect value, the compiler will
not allow it.
33
PowerBuilder data types in EAServer
34
CH A PTE R 3 Declarations
About this chapter This chapter explains how to declare variables, constants, and arrays and
refer to them in scripts, and how to declare remote procedure calls (RPCs)
and external functions that reside in dynamic link libraries (DLLs).
Contents
Topic Page
Declaring variables 36
Declaring constants 49
Declaring arrays 50
Declaring external functions 60
Declaring DBMS stored procedures as remote procedure calls 67
(RPCs)
35
Declaring variables
Declaring variables
General information Before you use a variable in a PowerBuilder script, you must declare it (give it
a data type and a name).
A variable can be a standard data type, a structure, or an object. Object data
types can be system objects as displayed in the Browser or they can be objects
you have defined by deriving them from those system object types. For most
variables, you can assign it a value when you declare it. You can always assign
it a value within a script.
Global declarations Global variables can be defined in the Script view of the Application, Window,
User Object, Function, or Menu painters:
36
Chapter 3 Declarations
• Select Declare from the first dropdown listbox in the Script view
• Select Global Variables in the second dropdown listbox of the Script view
• Type the declaration in the scripting area of the Script view
Instance and shared Instance and shared variables belong to particular objects: windows, user
declarations objects, menus, or the application object. Before you can declare them, you
must open the object in its painter. Then you must:
• Select Declare from the first dropdown listbox in the Script view
• Select Instance Variables or Shared Variables in the second dropdown
listbox of the Script view
• Type the declaration in the scripting area of the Script view
Local declarations You declare local variables for an object or control in the script for that object
or control.
Declaring SQL You can also declare SQL cursors that are global, shared, instance, or local.
cursors Open a specific script or select a variable declaration scope in the Script view
and type the DECLARE SQL statement or select Paste SQL from the
PainterBar or popup menu.
37
Declaring variables
Referring to global To refer to a global variable, you specify its name in a script. However, if the
variables global variable has the same name as a local or shared variable, the local or
shared variable will be found first.
To refer to a global variable that is masked by a local or shared variable of the
same name, use the global scope operator (::) before the name:
::globalname
For example, this statement compares the value of local and global variables,
both named total:
IF total < ::total THEN ...
Referring to instance You can refer to an instance variable in a script if there is an instance of the
variables object open in the application. Depending on the situation, you may need to
qualify the name of the instance variable with the name of the object defining
it.
Using unqualified names You can refer to instance variables without
qualifying them with the object name in the following cases:
• For application-level variables, in scripts for the application object
• For window-level variables, in scripts for the window itself and in scripts
for controls in that window
• For user-object-level variables, in scripts for the user object itself and in
scripts for controls in that user object
• For menu-level variables, in scripts for a menu object, either the highest-
level menu or scripts for the menu objects included as items on the menu
For example, if w_emp has an instance variable EmpID, then you can reference
EmpID without qualification in any script for w_emp or its controls such as:
sle_id.Text = EmpID
Using qualified names In all other cases, you need to qualify the name of
the instance variable with the name of the object using dot notation:
object.instancevariable
(Of course, this requirement applies only to Public instance variables. You
cannot reference Private instance variables outside the object at all, qualified
or not.)
For example, to refer to the w_emp instance variable EmpID from a script
outside the window, you need to qualify the variable with the window name:
sle_ID.Text = w_emp.EmpID
38
Chapter 3 Declarations
39
Declaring variables
Full syntax The full syntax allows you to specify access and an initial value. Arrays and
some data types, such as blobs and decimals, accept additional information:
{ access } datatype { { size } } { { precision } } variablename { = value }
{, variablename2 { = value2 } }
Parameter Description
access (For instance variables only) Keywords specifying the
(optional) access for the variable
For information, see "Access for instance variables" on
page 45
datatype The data type of the variable. You can specify a standard
data type, a system object, or a previously defined structure
For blobs and decimals, you can specify the size or
precision of the data by including an optional value in
brackets
{ size } (For blobs only) A number, enclosed in braces, specifying
(optional) the size in bytes of the blob. If { size } is omitted, the blob
has an initial size of zero and PowerBuilder adjusts its size
each time it is used during execution
If you enter a size that exceeds the declared length in a
script, PowerBuilder truncates the blob data
{ precision } (For decimals only) A number, enclosed in braces,
(optional) specifying the number of digits after the decimal point; if
you don’t specify a precision, the variable takes the
precision assigned to it in the script
variablename The name of the variable (must be a valid PowerScript
identifier, as described in "Identifier names" on page 6)
You can define additional variables with the same data type
by naming additional variable names, separated by
commas; each variable can have a value
value A literal or expression of the appropriate data type that will
(optional) be the initial value of the variable
Blobs cannot be initialized with a value
For information, see "Initial values for variables" on page
42
40
Chapter 3 Declarations
41
Declaring variables
Variable names
General information In a well-planned application, standards determine how you will name your
PowerScript variables. Naming conventions make scripts easy to understand
and help you avoid name conflicts. A typical approach is to include a prefix
that identifies the scope and the data type of the variable. For example, a prefix
for an instance variable’s name typically begins with i (such as ii_count or
is_empname), a local integer variable’s name would be li_total and a global
integer variable’s name would be gi_total.
For information about naming conventions, see Application Techniques.
X and Y as variable Although you may think of x and y as typical variable names, in PowerBuilder
names they are also properties that specify an object’s onscreen coordinates. If you use
them as variables and forget to declare them, you will not get a compiler error.
PowerBuilder will assume you want to move the object, which may lead to
unexpected results in your application.
42
Chapter 3 Declarations
Specifying a literal as To initialize a variable when you declare it, place an equal sign (=) and a literal
a initial value appropriate for that variable data type after the variable. For information about
literals for specific data types, see "Standard data types" on page 24.
This example declares li_count as an integer whose value is 5:
integer li_count=5
This example declares li_a and li_b as integers and initializes li_a to 5 and li_b
to 10:
integer li_a=5, li_b=10
This example initializes ls_method with the string "UPS":
string ls_method="UPS"
This example initializes ls_headers to three words separated by tabs:
string ls_headers = "Name~tAddress~tCity"
This example initializes li_a to 1 and li_c to 100, leaving li_b set to its default
value of zero:
integer li_a=1, li_b, li_c=100
This example declares ld_StartDate as a date and initializes it with the date Feb
1, 1993:
date ld_StartDate = 1993-02-01
Specifying an You can initialize a variable with the value of an existing variable or
expression as an expression, such as:
initial value
integer i = 100
integer j = i
When you do this, the second variable is initialized with the value of the
expression when the script is compiled. The initialization is not reevaluated
during execution.
If the expression’s value changes Because the expression’s value is set to
the variable when the script is compiled (not during execution) make sure the
expression is not one whose value is based on current conditions. If you want
to specify an expression whose value will be different when the application is
executed, do not initialize the variable in the declaration. For such values,
declare the variable and assign the value in separate statements.
Unwanted result In this declaration, the value of d is the date the script is
compiled:
date d_date = Today( )
43
Declaring variables
Wanted result In contrast, these statements result in d being set to the date the
application is run:
date d_date
d_date = Today( )
How shared variables When you use a shared variable in a script, the variable is initialized when the
are initialized first instance of the object is opened. When the object is closed, the shared
variable continues to exist until you exit the application. If you open the object
again without exiting the application, the shared variable will have the value it
had when you closed the object.
For example, if you set the shared variable Count to 20 in the script for a
window, then close the window, and then reopen the window without exiting
the application, Count will be equal to 20.
How instance When you define an instance variable for a window, menu, or application
variables are object, the instance variable is initialized when the object is opened. Its initial
initialized
value is the default value for its data type or the value specified in the variable
declarations.
When you close the object, the instance variable ceases to exist. If you open the
object again, the instance variable is initialized again.
When to use multiple instances of windows When you build a script for
one of multiple instances of a window, instance variables can have a different
value in each instance of the window. For example, to set a flag based on the
contents of the instance of a window, you would use an instance variable.
When to use shared variables instead Use a shared variable instead of an
instance variable if you need a variable that:
• Keeps the same value over multiple instances of an object
• Continues to exist after the object is closed
44
Chapter 3 Declarations
45
Declaring variables
Parameter Description
writeaccess A keyword restricting the ability of scripts to change the
(optional) variable’s value. Values are:
• PROTECTEDWRITE — Only scripts for the object and
its descendants can change the variable
• PRIVATEWRITE — Only scripts for the object can
change the variable
When access-right is PUBLIC, you can specify either
keyword. When access-right is PROTECTED, you can
specify only PRIVATEWRITE. You cannot specify a
modifier for PRIVATE access, because PRIVATE is already
fully restricted
If writeaccess is omitted, any script can change the variable
datatype A valid data type. See "Syntax of a variable declaration" on
page 39
variablename A valid identifier. See "Syntax of a variable declaration" on
page 39
Usage Access modifiers give you more control over which objects have access to a
particular object’s variables. A typical use is to declare a public variable but
only allow the owner object to modify it:
public protectedwrite integer ii_count
You can also group declarations that have the same access by specifying the
access-right keyword as a label (see "Another format for access-right
keywords" next).
When you look at exported object syntax, you may see the access modifiers
SYSTEMREAD and SYSTEMWRITE. Only PowerBuilder can access
variables with these modifiers. You cannot refer to variables with these
modifiers in your scripts and functions and you cannot use these modifiers in
your own definitions.
Examples To declare these variables, select Declare>Instance Variables in the appropriate
painter.
These declarations use access keywords to control the scripts that have access
to the variables:
private integer ii_a, ii_n
public integer ii_Subtotal
protected integer ii_WinCount
This protected variable can only be changed by scripts of the owner object;
descendants of the owner can read it:
46
Chapter 3 Declarations
47
Declaring variables
Within a labeled group of declarations, you can override the access on a single
line by specifying another access-right keyword with the declaration. The
labeled access takes effect again on the following lines.
Examples In these declarations, the instance variables have the access specified by the
label that precedes them. Another private variable is defined at the end, where
private overrides the public label:
Private:
integer ii_a=10, ii_b=24
string is_Name, is_Address1
Protected:
integer ii_Units
double idb_Results
string is_Lname
Public:
integer ii_Weight
string is_Location="Home"
private integer ii_test
Some of these protected declarations have restricted write access:
Protected:
integer ii_Units
privatewrite double idb_Results
privatewrite string is_Lname
48
Chapter 3 Declarations
Declaring constants
Description Any PowerScript variable declaration of a standard data type that can be
assigned an initial value can be a constant instead of a variable. To make it a
constant, include the keyword CONSTANT in the declaration and assign it an
initial value.
Syntax CONSTANT { access } datatype constname = value
Parameter Description
CONSTANT Declares a constant instead of a variable. The CONSTANT
keyword can be before or after the access keywords
access (For instance variables only) Keywords specifying the
(optional) access for the constant
For information, see "Access for instance variables" on
page 45
datatype A standard data type for the constant. For decimals, you can
include an optional value in brackets to specify the
precision of the data. Blobs cannot be constants
For information about PowerBuilder data types, see
"Standard data types" on page 24
constname The name of the constant (must be a valid PowerScript
identifier, as described in "Identifier names" on page 6)
value A literal or expression of the appropriate data type that will
be the value of the constant. The value is required
For information, see "Initial values for variables" on page
42
49
Declaring arrays
Declaring arrays
Description An array is an indexed collection of elements of a single data type. In
PowerBuilder, an array can have one or more dimensions. One-dimensional
arrays can have a fixed or variable size; multidimensional arrays always have
a fixed size. Each dimension of an array can have 2,147,483,647 bytes of
elements.
Any simple variable declaration becomes an array when you specify brackets
after the variable name. For fixed-size arrays, you specify the sizes of the
dimensions inside those brackets.
Syntax { access } datatype variablename { d1, ..., dn } { = { valuelist } }
Parameter Description
access (For instance variables only) Keywords specifying the
(optional) access for the variable
For information, see "Access for instance variables" on
page 45
datatype The data type of the variable. You can specify a standard
data type, a system object, or a previously defined
structure
For decimals, you can specify the precision of the data by
including an optional value in brackets after datatype (see
"Syntax of a variable declaration" on page 39):
decimal {2} variablename [ ]
For blobs, fixed-length blobs within an array are not
supported. If you specify a size after datatype, it is ignored
variablename The name of the variable (name must be a valid
PowerScript identifier, as described in "Identifier names"
on page 6)
You can define additional arrays with the same data type
by naming additional variable names with brackets and
optional value lists, separated by commas
50
Chapter 3 Declarations
Parameter Description
[ { d1, ..., dn } ] Brackets and (for fixed-size arrays) one or more integer
values (d1 through dn, one for each dimension) specifying
the sizes of the dimensions
For a variable-size array, which is always 1-dimensional,
specify brackets only
For more information on how variable-size arrays change
size, see "Size of variable-size arrays" on page 54
For a fixed-size array, the number of dimensions is
determined by the number of integers you specify and is
limited only by the amount of available memory
For fixed-size arrays, you can use TO to specify a range of
element numbers (instead of a dimension size) for one or
more of the dimensions. Specifying TO allows you to
change the lower bound of the dimension (upperbound
must be greater than lowbound):
[
d1lowbound TO d1upperbound {, ... ,
dnlowbound TO dnupperbound }
]
{ valuelist } A list of initial values for each position of the array. The
(optional) values are separated by commas and the whole list is
enclosed in braces. The number of values cannot be greater
than the number of positions in the array. The data type of
the values must match datatype
51
Declaring arrays
52
Chapter 3 Declarations
Assigning values
You can assign values to an array after declaring it using the same syntax of a
list of values within braces:
integer li_Arr[]
Li_Arr = {1, 2, 3, 4}
53
Declaring arrays
54
Chapter 3 Declarations
How memory is Initializing elements of a variable-size array allocates memory for those
allocated elements. You specify initial values just as you do for fixed-size arrays, by
listing the values in braces. The following statement sets code[1] equal to 11,
code[2] equal to 242, and code[3] equal to 27. The array has a size of 3 initially,
but the size will change if you assign values to higher positions:
integer li_code[ ]={11,242,27}
For example, these statements declare a variable-size array and assigns values
to three array elements:
long ll_price[ ]
ll_price[100] = 2000
ll_price[50] = 3000
ll_price[110] = 5000
When these statements first execute, they allocate memory as follows:
• The statement ll_price[100]=2000 will allocate memory for 100 long
numbers ll_price[1] to ll_price[100], then assign 0 (the default for
numbers) to ll_price[1] through ll_price[99] and assign 2000 to
ll_price[100].
• The statement ll_price[50]=3000 will not allocate more memory but will
assign the value 3000 to the 50th element of the ll_price array.
• The statement ll_price[110]=5000 will allocate memory for 10 more long
numbers named ll_price[101] to ll_price[110] and then assign 0 (the
default for numbers) to ll_price[101] through ll_price[109] and assign
5000 to ll_price[110].
55
Declaring arrays
56
Chapter 3 Declarations
57
Declaring arrays
1 4
2 5
3 6
58
Chapter 3 Declarations
1 3 5 0
2 4 6 0
59
Declaring external functions
60
Chapter 3 Declarations
Parameter Description
FUNCTION or A keyword specifying the type of call, which determines the
SUBROUTINE way return values are handled. If there is a return value, declare
it as a FUNCTION; if it returns nothing or returns VOID,
specify SUBROUTINE
returndatatype The data type of the value returned by the function
name The name of a function or subroutine that resides in a DLL
REF Specifies that you are passing by reference the argument that
follows REF. The function can store a value in arg that will be
accessible to the rest of the PowerBuilder script
datatype arg The data type and name of the arguments for the function or
subroutine. The list must match the definition of the function in
the DLL. Each datatype arg pair can be preceded by REF
For more information on passing arguments, see Application
Techniques
LIBRARY The LIBRARY keyword is followed by a string containing the
"libname" name of the dynamic library in which the function or
subroutine is stored. libname is a dynamic link library, which
is a file that usually has an extension DLL or EXE on
Windows. For components deployed to EAServer on UNIX,
the file has an extension of .so, .sl, or .a depending on the
operating system
ALIAS FOR Keywords followed by a string giving the name of the function
"extname" as defined in the dynamic library. If the name in the dynamic
(optional) library is not the name you want to use in your script or if the
name in the database is not a legal PowerScript name, you must
specify ALIAS FOR "extname" to establish the association
between the PowerScript name and the external name
Use of the access keyword with local external functions works the same as the
access-right keywords for instance variables.
61
Declaring external functions
62
Chapter 3 Declarations
uint lui_numdevs
lui_numdevs = WaveOutGetNumDevs()
IF lui_numdevs > 0 THEN
sndPlaySoundA(as_filename,ai_option)
RETURN 1
ELSE
RETURN -1
END IF
Example 2 This is the declaration for the Win32 GetSysColor function:
FUNCTION ulong GetSysColor (int index) LIBRARY
"USER32.DLL"
This statement calls the external function. The meanings of the index argument
and the return value are specified in the Win32 documentation:
RETURN GetSysColor (ai_index)
Example 3 This is the declaration for the Win32 GetSysColor function:
FUNCTION int GetSystemMetrics (int index) LIBRARY
"USER32.DLL"
These statements call the external function to get the screen height and width:
RETURN GetSystemMetrics(1)
RETURN GetSystemMetrics(0)
63
Declaring external functions
Use the tables to find out what PowerBuilder data type to use in an external
function declaration. The PowerBuilder data type you select depends on the
data type in the source code for the function. The first column lists data types
in source code. The second column describes the data type so you know exactly
what it is. The third column lists the PowerBuilder data type you should use in
the external function declaration.
Boolean BOOL on Windows is 16-bit, signed. It is declared in PowerBuilder as
boolean.
Pointers
Data type in source
code Size, sign, precision PowerBuilder data type
* (any pointer) 32-bit pointer Long
char * Array of bytes of Blob
variable length
Reference arguments
When you pass a string to an external function by reference, all memory
management is done in PowerBuilder. The string variable must be long enough
to hold the returned value. To ensure that this is true, first declare the string
variable and then use the Space function to fill the variable with blanks equal
to the maximum number of characters that you expect the function to return.
64
Chapter 3 Declarations
Fixed-point values
Data type in source PowerBuilder data
code Size, sign, precision type
short 16 bits, signed Integer
unsigned short 16 bits, unsigned UnsignedInteger
int 32 bits, signed Long
unsigned int 32 bits, unsigned UnsignedLong
long 32 bits, signed Long
unsigned long 32 bits, unsigned UnsignedLong
65
Declaring external functions
66
Chapter 3 Declarations
67
Declaring DBMS stored procedures as remote procedure calls (RPCs)
Argument Description
RPCFUNC A keyword indicating that this declaration is for a stored
procedure in a DBMS, not an external function in a DLL
For information on declaring external functions, see
"Declaring external functions" on page 60
ALIAS FOR Keywords followed by a string naming the procedure in the
"spname" database. If the name in the database is not the name you want
(optional) to use in your script or if the name in the database is not a legal
PowerScript name, you must specify ALIAS FOR "spname" to
establish the association between the PowerScript name and
the database name
Usage If a function does not return a value (for example, it returns Void), specify the
declaration as a subroutine instead of a function.
RPC declarations are always associated with a transaction object. You declare
them as local external functions. The Declare Local External Functions dialog
has a Procedures button (if the connected database supports stored procedures),
which gives you access to a list of stored procedures in the database.
For more information, see Application Techniques.
Examples Example 1 This declaration of the GIVE_RAISE_PROC stored procedure is
declared in the User Object painter for a transaction object (the declaration
appears on one line):
FUNCTION double GIVE_RAISE(ref double SALARY) RPCFUNC
ALIAS FOR "GIVE_RAISE_PROC"
This code calls the function in a script:
double val = 20000
double rv
rv = SQLCA.give_raise(val)
Example 2 This declaration for the stored procedure SPM8 doesn’t need an
ALIAS FOR phrase, because the PowerBuilder and DBMS names are the
same:
FUNCTION integer SPM8(integer value) RPCFUNC
This code calls the SPM8 stored procedure:
int myresult
myresult = SQLCA.spm8(myresult)
IF SQLCA.sqlcode <> 0 THEN
messagebox("Error", SQLCA.sqlerrtext)
END IF
68
CH A PTE R 4 Operators and Expressions
About this chapter This chapter describes the operators supported in PowerScript and how to
use them in expressions.
Contents
Topic Page
Operators in PowerBuilder 70
Operator precedence in PowerBuilder expressions 75
Data type of PowerBuilder expressions 76
69
Operators in PowerBuilder
Operators in PowerBuilder
General information Operators perform arithmetic calculations; compare numbers, text, and
boolean values; execute relational operations on boolean values; and
concatenate strings and blobs.
Three types PowerScript supports three types of operators:
• Arithmetic operators for numeric data types
• Relational operators for all data types
• Concatenation operator for string data types
Usage Operator shortcuts for assignments For information about shortcuts that
combine arithmetic operators with assignments (such as ++ and +=), see
Assignment on page 124.
Subtraction If the option Allow Dashes in Identifiers is checked on the
Script tab in the Options dialog box, you must always surround the subtraction
operator and the -- operator with spaces. Otherwise, PowerBuilder interprets
the expression as an identifier.
For information about dashes in identifiers, see "Identifier names" on page 6.
70
Chapter 4 Operators and Expressions
SetNULL(c)
71
Operators in PowerBuilder
a = b*c
a = b/c
Overflow This example illustrates the value of the variable i after overflow
occurs:
integer i
i = 32767
i = i + 1 // i is now -32768
72
Chapter 4 Operators and Expressions
NULL value evaluations When you form a boolean expression that contains
a NULL value, the AND and OR operators behave differently. Thinking of
NULL as undefined (neither TRUE nor FALSE) makes the results easier to
calculate.
For more information about NULL values, see "NULL values" on page 11.
Examples Case-sensitive comparisons If you compare two strings with the same text
but different case, the comparison fails. But if you use the Upper or Lower
function, you can ensure that the case of both strings are the same so that only
the content affects the comparison:
City1="Austin"
City2="AUSTIN"
IF City1=City2 ... // Will return FALSE
City1="Austin"
City2="AUSTIN"
IF Upper(City1)=Upper(City2)... // Will return TRUE
Trailing blanks in comparisons In this example, trailing blanks in one
string cause the comparison to fail:
City1="Austin"
City2="Austin "
IF City1=City2 ... // Will return FALSE
Logical expressions with NULL values In this example, the expressions
involving the variable f, which has been set to NULL, have NULL values:
boolean d, e = TRUE, f
SetNull(f)
d = e and f // d is NULL
d = e or f // d is TRUE
73
Operators in PowerBuilder
74
Chapter 4 Operators and Expressions
How to override To override the order, enclose expressions in parentheses. This identifies the
group and order in which PowerBuilder will evaluate the expressions. When
there are nested groups, the groups are evaluated from the inside out.
For example, in the expression (x+(y*(a+b))), a+b is evaluated first. The sum
of a and b is then multiplied by y, and this product is added to x.
75
Data type of PowerBuilder expressions
76
Chapter 4 Operators and Expressions
Out of range
Integer literals beyond the range of UnsignedLong cause compiler errors.
77
Data type of PowerBuilder expressions
78
Chapter 4 Operators and Expressions
• Special characters (such as newline, formfeed, octal, hex, and so on) can
be assigned to char variables using string conversion, such as:
char c = "~n"
String variables assigned to char variables also convert using these rules. A
char variable assigned to a string variable results in a one-character string.
Assigning strings to As with other data types, you can use arrays of chars. Assigning strings to char
char arrays arrays follows these rules:
• If the char array is unbounded (defined as a variable-size array), the
contents of the string are copied directly into the char array.
• If the char array is bounded and its length is less than or equal to the length
of the string, the string is truncated in the array.
• If the char array is bounded and its length is greater than the length of the
string, the entire string is copied into the array along with its zero
terminator. Remaining characters in the array are undetermined.
Assigning char arrays When a char array is assigned to a string variable, the contents of the array are
to strings copied into the string up to a zero terminator, if found, in the char array.
Using both strings and Expressions using both strings and char arrays promote the chars to strings
chars in an expression before evaluation. For example:
char c
. . .
if (c = "x") then
promotes the contents of c to a string before comparison with the string "x".
Using chars in All PowerScript functions that take strings also take chars and char arrays,
PowerScript functions subject to the conversion rules described above.
79
Data type of PowerBuilder expressions
80
CH A PTE R 5 Structures and Objects
About this chapter This chapter describes basic concepts for structures and objects and how
you define, declare, and use them in PowerScript.
Contents
Topic Page
About structures 82
About objects 84
Assignment for objects and structures 90
81
About structures
About structures
General information A structure is a collection of one or more variables (sometimes called
elements) that you want to group together under a single name. The variables
can have any data type, including standard and object data types and other
structures.
Defining structures When you define a structure in the PowerBuilder Structure painter or an object
painter (such as Window, Menu, or User Object), you are creating a structure
definition. To use the structure, you must declare it. When you declare it, an
instance of it is automatically created for you. When it goes out of scope, the
structure is destroyed.
For details about defining structures, see the PowerBuilder User’s Guide.
Declaring structures If you have defined a global structure in the Structure painter called
str_emp_data, you can declare an instance of the structure in a script or in an
object’s instance variables. If you define the structure in an object painter, you
can only declare instances of the structure in the object’s instance variables and
scripts.
This declaration declares two instances of the structure str_emp_data:
str_emp_data str_emp1, str_emp2
Referring to structure In scripts, you refer to the structure’s variables using dot notation:
variables
structurename.variable
These statements assign values to the variables in str_emp_data:
str_emp1.emp_id = 100
str_emp1.emp_lname = "Jones"
str_emp1.emp_salary = 200
str_emp2.emp_id = 101
str_emp2.emp_salary = str_emp1.salary * 1.05
Using structures as If the structure is declared as part of an object, you can qualify the structure
instance variables name using dot notation:
objectname.structurename.variable
Suppose that this declaration is an instance variable of the window
w_customer:
str_cust_data str_cust1
82
Chapter 5 Structures and Objects
This statement in a script for the object refers to a variable of str_cust_data (the
pronoun This is optional, because the structure declaration is part of the
object):
This.str_cust1.name
This statement in a script for some other object qualifies the structure with the
window name:
w_customer.str_cust1.name
83
About objects
About objects
What an object is In object-oriented programming, an object is a self-contained module
containing state information and associated methods. Most entities in
PowerBuilder are objects: visual objects such as windows and controls on
windows, nonvisual objects such as transaction and error objects, and user
objects that you design yourself.
An object class is a definition of an object. You create an object’s definition in
the appropriate painter: Window, Menu, Application, Structure, or User Object
painter. In the painter, you add controls to be part of the object, specify initial
values for the object’s properties, define its instance variables and functions,
and write scripts for its events and functions.
An object instance is an occurrence of the object created during the execution
of your application. Your code instantiates an object when it allocates memory
for the object and defines the object based on the definition in the object class.
An object reference is your handle to the object instance. To interact with an
object, you need its object reference. You can assign an object reference to a
variable of the appropriate type.
System objects versus There are two categories of objects supported by PowerBuilder: system objects
user objects (also referred to as system classes) defined by PowerBuilder and user objects
you in define in painters.
System objects The PowerBuilder system objects or classes are inherited
from a base class PowerObject. The system classes are the ancestors of all the
objects you define. To see the system class hierarchy, look at the System tab in
the Browser.
User objects You can create user object class definitions in several painters:
Window, Menu, Application, Structure, and User Object painters. The objects
you define are inherited from one of the system classes or another of your
classes.
Some painters use many classes. In the Window and User Object painters, your
main definition is inherited from the window or user object class. The controls
you use are also inherited from the system class for that control.
84
Chapter 5 Structures and Objects
Class user objects Class user objects consist of properties, functions, and sometimes events. They
have no visual component. There are two types—standard and custom:
Class user objects Description
Standard Inherits its definition from a nonvisual PowerBuilder
object, such as the Transaction or Error object. You can
add instance variables and functions
A few nonvisual objects have events—to write scripts
for these events, you have to define a class user object
Custom An object of your own design for which you define
instance variables, events, and functions in order to
encapsulate application-specific programming in an
object
For information on defining and using user objects, see the PowerBuilder
User’s Guide.
85
About objects
Instantiating objects
Classes versus Because of the way PowerBuilder object classes and instances are named, it’s
instances easy to think they are the same thing. For example, when you define a window
in the Window painter, you are defining an object class.
One instance When you open a window with the simplest format of the Open function, you
are instantiating an object instance. Both the class definition and the instance
have the same name. In your application, w_main is a global variable of type
w_main:
Open(w_main)
When you open a window this way, you can only open one instance of the
object.
Several instances If you want to open more than one instance of a window class, you need to
define a variable to hold each object reference:
w_main w_1, w_2
Open(w_1)
Open(w_2)
You can also open windows by specifying the class in the Open function:
window w_1, w_2
Open(w_1, "w_main")
Open(w_2, "w_main")
For class user objects, you always define a variable to hold the object reference
and then instantiate the object with the CREATE statement:
uo_emp_data uo_1, uo_2
uo_1 = CREATE uo_emp_data
uo_2 = CREATE uo_emp_data
You can have more than one reference to an object. You might assign an object
reference to a variable of the appropriate type. Or you might pass an object
reference to another object so that it can change or get information from the
object.
For more information about object variables and assignment, see "User objects
that behave like structures" on page 88.
86
Chapter 5 Structures and Objects
Garbage collection
What garbage The PowerBuilder garbage collection mechanism checks memory
collection does automatically for unreferenced and orphaned objects and removes any it finds,
thus taking care of most memory leaks. You can use garbage collection to
destroy objects instead of explicitly destroying them using the DESTROY
statement. This lets you avoid execution-time errors that occur when you
destroy an object that was being used by another process or had been passed by
reference to a posted event or function.
When garbage Garbage collection occurs:
collection occurs
• When a reference is removed from an object A reference to an
object is any variable whose value is the object. When the variable goes
out of scope, or when it is assigned a different value, PowerBuilder
removes a reference to the object, counts the remaining references, and
destroys the object if no references remain.
• When the garbage collection interval is exceeded When
PowerBuilder completes the execution of a system-triggered event, it
makes a garbage collection pass if the set interval between garbage
collection passes has been exceeded. The default interval is 0.5 seconds.
The garbage collection pass removes any objects and classes that cannot
be referenced, including those containing circular references (otherwise
unreferenced objects that reference each other).
87
About objects
Exceptions to garbage There are a few objects that are prevented from being collected:
collection
• Visual objects Any object that is visible on your screen is not collected
because when the object is created and displayed on your screen, an
internal reference is added to the object. When any visual object is closed
it is explicitly destroyed.
• Timing objects Any Timing object that is currently running is not
collected because the Start function for a Timing object adds an internal
reference. The Stop function removes the reference.
• Shared objects Registered shared objects are not collected because the
SharedObjectRegister function adds an internal reference.
SharedObjectUnregister removes the internal reference.
Controlling when Garbage collection occurs automatically in PowerBuilder, but you can use the
garbage collection functions GarbageCollect, GarbageCollectGetTimeLimit, and
occurs
GarbageCollectSetTimeLimit to force immediate garbage collection or to
change the interval between reference count checks. By setting the interval
between garbage collection passes to a very large number, you can effectively
turn off garbage collection.
88
Chapter 5 Structures and Objects
Memory allocation Memory allocation is different for user objects and structures. An object
differences variable is a reference to the object. Declaring the variable does not allocate
memory for the object. After you declare it, you must instantiate it with a
CREATE statement. Assignment for a user object is also different (described
in the next section).
Autoinstantiated If you want a user object that has methods and inheritance but want the memory
objects allocation of a structure, you can define an autoinstantiated object.
You do not have to create and destroy autoinstantiated objects. Like structures,
they are created when they are declared and destroyed when they go out of
scope. However, because assignment for autoinstantiated objects behaves like
structures, the copies made of the object can be a drawback.
To make a custom class user object autoinstantiated, select the Autoinstantiate
checkbox on the user object’s property sheet.
89
Assignment for objects and structures
When you assign a structure to another structure, the whole structure is copied
and a second copy of the structure data exists:
str_emp1 = str_emp2
The assignment copies the whole structure from one structure variable to the
other. Each variable is a separate instance of the structure str_emp_data.
Restriction on assignment If the structures have different definitions, you
cannot assign one to another, even if they have the same set of variable
definitions.
For example, this assignment is not allowed:
str_emp str_person1
str_cust str_person2
str_person2 = str_person1 // Not allowed
For information about passing structures as function arguments, see "Passing
arguments to functions and events" on page 108.
Assignment for Declaring an object variable declares an object reference:
objects
uo_emp_data uo_emp1, uo_emp2 // Two object references
Using the CREATE statement creates an instance of the object:
uo_emp1 = CREATE uo_emp_data
When you assign one object variable to another, a reference to the object
instance is copied. Only one copy of the object exists:
uo_emp2 = uo_emp1 // Both point to same object instance
90
Chapter 5 Structures and Objects
91
Assignment for objects and structures
92
CH A PTE R 6 Calling Functions and Events
About this chapter This chapter provides background information that will help you
understand the different ways you can use functions and events. It then
provides the syntax for calling functions and events.
Contents
Topic Page
About functions and events 94
Syntax for calling PowerBuilder functions and events 113
Calling functions and events in an object’s ancestor 117
93
About functions and events
94
Chapter 6 Calling Functions and Events
Functions versus Functions and events have several similarities as well as a many differences:
events
Similarities Differences
Both functions and events have Events are only associated with objects.
arguments and return values Functions can be global or part of an
object’s definition
You can call object functions and PowerBuilder uses a different search order
events dynamically or statically when looking for an event versus a function
(global or system functions cannot be
called dynamically)
95
About functions and events
Similarities Differences
You can post or trigger the function or A call to an undefined event will not trigger
event call an error, but a call to an undefined function
will
Functions can be overloaded whereas
events cannot
When you define a function, you can
restrict access to it. You cannot add scope
restrictions when you define events
You can easily extend or override ancestor
events when you are writing scripts in a
descendant object, and you override
functions in the same way. To extend the
ancestor function, you can call it in the
descendant’s version of the function
Which to use Whether you write most of your code in user-defined functions
or in event scripts is one of the design decisions you will make. Because there
is no performance difference, the decision will be based on how you prefer to
interact with PowerBuilder: whether you prefer the interface for defining user
events or that for defining functions, how you want to handle errors, and
whether your design includes overloading.
It is unlikely that you will use either events or functions exclusively. But for
ease of maintenance, you will want to choose one approach for handling most
situations.
96
Chapter 6 Calling Functions and Events
Using functions with the same name but different arguments is called function
overloading. For more information, see "Overloading, overriding, and
extending functions and events" on page 106.
Unqualified function names If you don’t qualify a function name with an
object, PowerBuilder searches for the function and executes the first one it
finds that matches the name and arguments. It searches for a match in the
following order:
1 A global external function
2 A global function
3 An object function and local external function (if the object is a
descendant, PowerBuilder searches upward through the ancestor
hierarchy to find a match for the function prototype)
4 A system function
Qualified function names You can qualify an object function using dot
notation to ensure that the object function (and not a global function of the
same name) is found. With a qualified name, the search for a matching function
involves the ancestor hierarchy only (item 3 in search list above) as shown in
the following examples of function calls:
dw_1.Update( )
w_employee.uf_process_list()
This.uf_process_list()
When PowerBuilder is searching the ancestor hierarchy for a function, you can
specify that you want to call an ancestor function instead of a matching
descendent function.
For the syntax for calling ancestor functions, see "Calling functions and events
in an object’s ancestor" on page 117.
Finding events PowerBuilder events in descendent objects are by default extensions of
ancestor events. PowerBuilder searches for events in the object’s ancestor
hierarchy until it gets to the top ancestor or finds an event that overrides its
ancestor. Then it begins executing the events, from the ancestor event down to
the descendent event.
97
About functions and events
Finding functions The following illustration shows the difference between searching for events
versus events and searching for functions:
98
Chapter 6 Calling Functions and Events
99
About functions and events
Specifying static or For object functions and events, you can choose when PowerBuilder looks for
dynamic lookup them by specifying static or dynamic lookup. You specify static or dynamic
lookup using the STATIC or DYNAMIC keywords. The DYNAMIC keyword
applies only to functions that are associated with an object. You cannot call
global or system functions dynamically.
Static calls
Static is the default By default, PowerBuilder makes static lookups for functions and events. This
means that it identifies the function or event by matching the name and
argument types when it compiles the code. A matching function or event must
exist in the object at compile time.
100
Chapter 6 Calling Functions and Events
Results of static calls Static calls do not guarantee that the function or event identified at compile
time is the one that is executed. Suppose that you define a variable of an
ancestor type and it has a particular function definition. If you assign an
instance of a descendent object to the variable and the descendant has a
function that overrides the ancestor’s function (the one found at compile time),
the function in the descendant is executed.
Dynamic calls
You specify dynamic When you specify a dynamic call in PowerBuilder, the function or event does
calls not have to exist when you compile the code. You are saying to the compiler:
trust me—there will be a suitable function or event available at execution time.
For a dynamic call, PowerBuilder waits until it is time to execute the function
or event to look for it. This gives you flexibility and allows you to call functions
or events in descendants that don’t exist in the ancestor.
Results of dynamic To illustrate the results of dynamic calls, consider these objects:
calls
• Ancestor window w_a with a function Set(integer).
• Descendent window w_a_desc with two functions. Set(integer) overrides
the ancestor function. Set(string) overload of the function
Situation 1 Suppose you open the window mywindow of the ancestor
window class w_a:
w_a mywindow
Open(mywindow)
This is what happens when you call the Set function statically or dynamically:
This statement Has this result
mywindow.Set(1) Compiles correctly because function is found in
the ancestor w_a
At execution time, Set(integer) in the ancestor
is executed
mywindow.Set("hello") Fails to compile; no function prototype in w_a
matches the call
mywindow.DYNAMIC & Compiles successfully because of the
Set("hello")
DYNAMIC keyword
An error occurs at execution time because no
matching function is found
101
About functions and events
102
Chapter 6 Calling Functions and Events
The wf_export function called by the m_export item on the m_file menu does
not have a stubbed-out version in the ancestor window. This code for m_export
uses the DYNAMIC keyword to call wf_export. When the program is run, the
value of variable ish_currentsheet is a descendent window that does have a
definition for wf_export:
guo_global_vars.ish_currentsheet.DYNAMIC wf_export()
Errors when calling If you call a function or event dynamically, different conditions create different
functions and events results, from no effect to an execution error. The tables in this section illustrate
dynamically
this.
Functions Functions The rules for functions are similar to those for events, except
functions must exist: if a function is not found, an error always occurs. And
although events can exist without a script, if a function is defined it has to have
code.For purposes of illustration, the table below refers to these statements:
Statement 1 This statement calls a function without looking for a return
value:
object.DYNAMIC funcname( )
Statement 2 This statement looks for an integer return value:
int li_int
li_int = object.DYNAMIC funcname( )
Statement 3 This statement looks for an Any return value:
any la_any
la_any = object.DYNAMIC funcname( )
Events Events The table below describes different error conditions and refers to
these statements:
Statement 1 This statement calls an event without looking for a return value:
object.EVENT DYNAMIC eventname( )
103
About functions and events
104
Chapter 6 Calling Functions and Events
When an error occurs You can surround a dynamic method call in a try-
catch block to prevent the application from terminating when an execution
error occurs. Although you can also handle the error in the SystemError event,
you should not allow the application to continue once the SystemError event is
invoked—the SystemError event should only clean up and halt the application.
For information on using try-catch blocks, see the chapter on exception
handling in Application Techniques.
If the arguments don’t match Function arguments are part of the function’s
definition. Therefore, if the arguments don’t match (a compatible match, not an
exact match), it is essentially a different function. The result is the same as if
the function didn’t exist.
If you call an event dynamically and the arguments don’t match, the call fails
and control returns to the calling script. There is no error.
Error-proofing your code Calling functions and events dynamically opens
up your application to potential errors. The surest way to avoid these errors is
to always make static calls to functions and events. Short of that, your design
and testing can ensure that there will always be an appropriate function or event
with the correct return data type.
One type of error you can check for and avoid is data conversion errors.
The preceding tables illustrated that a function or event can return a NULL
value either as an Any variable or as a variable of the expected data type when
a function or event definition exists but is not implemented.
If you always assign return values to Any variables for dynamic calls, you can
test for NULL (which indicates failure) before using the value in code.
This example illustrates the technique of checking for NULL before using the
return value.
any la_any
integer li_gotvalue
la_any = object.DYNAMIC uf_getaninteger( )
IF IsNull(la_any) THEN
... // Error handling
ELSE
li_gotvalue = la_any
END IF
105
About functions and events
106
Chapter 6 Calling Functions and Events
When you call a function with an expression as an argument, the data type of
the expression may not be obvious. However, the data type is important in
determining what version of an overloaded function will be called.
Because of the intricacies of type promotion for numeric data types, you may
decide that you should not define overloaded functions with different numeric
data types. Changes someone makes later can affect the application more
drastically than expected if the change causes a different function to be called.
How type promotion works When PowerBuilder evaluates an expression, it
converts the data types of constants and variables so that it can process or
combine them correctly.
Numbers When PowerBuilder evaluates numeric expressions, it promotes
the data types of values according to the operators and the data types of the
other operands. For example, the data type of the expression n/2 is double
because it involves division—the data type of n doesn’t matter.
Strings When evaluating an expression that involves chars and strings,
PowerBuilder promotes chars to strings.
For more information on type promotion, see "Data type of PowerBuilder
expressions" on page 76.
Using conversion functions You can take control over the data types of
expressions by calling a conversion function. The conversion function ensures
that the data type of the expression matches the function prototype you want to
call.
For example, because the expression n/2 involves division, the data type is
double. However, if the function you want to call expects a long, you can use
the Long function to ensure that the function call matches the prototype:
CalculateHalf(Long(n/2))
107
About functions and events
No overloaded events
You cannot overload an event by defining an event with the same name but
different arguments. Event names must be unique.
To select To select extending or overriding, open the script in the Script view and check
or clear the Extend Ancestor Script item in the Edit or popup menu.
Passing objects When you pass an object to a function or event, the object must exist when you
refer to its properties and functions. If you call the function but the object has
been destroyed, you will get the execution error for a null object reference. This
is true whether you pass by reference, by value, or read-only.
108
Chapter 6 Calling Functions and Events
109
About functions and events
In the script that calls the function, you will either declare an array variable or
use an instance variable or value that has been passed to you. The declaration
of that variable, wherever it is, looks like this:
integer a[]
When you call the function, omit the brackets (because you are passing the
whole array). If you specified brackets, you would be passing one value from
the array:
uf_convertarray(a)
Fixed-size array as an argument For comparison, suppose the
uf_convertarray function accepts a fixed-size array of integers of 10 elements
instead. If the argument’s name is intarray, then for Name enter intarray[10] and
for Type enter integer.
The declaration of the variable to be passed looks like this:
integer a[10]
You call the function the same way, without brackets:
uf_convertarray(a)
Posting a function
If you post a function, you cannot use its return value.
User-defined functions and external functions may or may not return a value.
110
Chapter 6 Calling Functions and Events
Examples The built-in Asc function takes a string as an argument and returns
the ASCII value of the string’s first character:
string S1 = "Carton"
int Test
Test=32+Asc(S1) // Test now contains the value
// 99 (the ASCII value of "C"
// is 67).
The SelectRow function expects a row number as the first argument. The return
value of the GetRow function supplies the row number:
dw_1.SelectRow(dw_1.GetRow(), TRUE)
To ignore a return value, call the function as a single statement:
Beep(4) // This returns a value, but it is
// rarely needed.
Events Most system events return a value. The return value is a long—numeric codes
have specific meanings for each event. You specify the event’s return code with
a RETURN statement in the event script.
When the event is triggered by user actions or system messages, the value is
returned to the system, not to a script you write.
When you trigger a system or user-defined event, the return value is returned
to your script and you can use the value as appropriate. If you post an event,
you cannot use its return value.
111
About functions and events
Dynamic calls If you use the DYNAMIC keyword in a chain of cascaded calls, it carries over
to all function calls that follow.
In this example, both func1 and func2 are called dynamically:
object1.DYNAMIC func1().func2()
The compiler reports an error if you use DYNAMIC more than once in a
cascaded call. This example would cause an error:
object1.DYNAMIC func1().DYNAMIC func2() // error
Posted functions and Posted functions and events do not return a value to the calling scripts.
events Therefore, you can only use POST for the last function or event in a cascaded
call. Calls before the last must return a valid object that can be used by the
following call.
System events System events can only be last in a cascaded list of calls, because their return
value is a long (or they have no return value). They don’t return an object that
could be used by the next call.
An event you have defined can have a return value whose data type is an object.
You can include such events in a cascaded call.
112
Chapter 6 Calling Functions and Events
113
Syntax for calling PowerBuilder functions and events
Argument Description
argumentlist The values you want to pass to name. Each value in the list
(optional) must have a data type that corresponds to the declared data
type in the function or event definition or declaration
Calling arguments The type, calltype, and when keywords can be in any
order after objectname.
Not all options in the syntax apply to all types. For example, there’s no point
in calling a system PowerScript object function dynamically. It always exists,
and the dynamic call incurs extra overhead. However, if you had a user-defined
function of the same name that applied to a different object, you might call that
function dynamically.
User-defined global functions and system functions can be triggered or posted
but they cannot be called dynamically.
Finding functions If a global function does not exist with the given name,
PowerBuilder will look for an object function that matches the name and
argument list before it looks for a PowerBuilder system function.
Calling functions and events in the ancestor If you want to circumvent
the usual search order and force PowerBuilder to find a function or event in an
ancestor object, bypassing it in the descendant, you can use the ancestor
operator (::).
For more information about the scope operator for ancestors, see "Calling
functions and events in an object’s ancestor" on page 117.
Cascaded calls Calls can be cascaded using dot notation. Each function or
event call must return an object type that is the appropriate object for the
following call.
For more information about cascaded calls, see "Using cascaded calling and
return values" on page 111.
Using return values If the function has a return value, you can call the
function on the right side of an assignment statement, as an argument for
another function, or as an operand in an expression.
114
Chapter 6 Calling Functions and Events
External functions Before you can call an external function, you must
declare it. For information about declaring external functions, see "Declaring
external functions" on page 60.
Examples Example 1 The following statements show various function calls using the
most simple construction of the function call syntax.
This statement calls the system function Asc:
charnum = Asc("x")
This statement calls the DataWindow function in a script that belongs to the
DataWindow:
Update( )
This statement calls the global user-defined function gf_setup_appl:
gf_setup_appl(24, "Window1")
This statement calls the system function PrintRect:
PrintRect(job, 250, 250, 7500, 1000, 50)
Example 2 The following statements show calls to global and system
functions.
This statement posts the global user-defined function gf_setup_appl. The
function is executed when the calling script finishes:
POST gf_setup_appl(24, "Window1")
This statement posts the system function PrintRect. It is executed when the
calling script finishes. The print job specified in job must still be open:
POST PrintRect(job, 250, 250, 7500, 1000, 50)
Example 3 In a script for a control, these statements call a user-defined
function defined in the parent window. The statements are equivalent, because
FUNCTION, STATIC, and TRIGGER are the defaults:
Parent.FUNCTION STATIC TRIGGER wf_process( )
Parent.wf_process( )
Example 4 This statement in a DataWindow control’s Clicked script calls
the DoubleClicked event for the same control. The arguments the system
passed to Clicked are passed on to DoubleClicked. When triggered by the
system, PowerBuilder passes DoubleClicked those same arguments:
This.EVENT DoubleClicked(xpos, ypos, row, dwo)
This statement posts the same event:
This.EVENT POST DoubleClicked(xpos, ypos, row, dwo)
115
Syntax for calling PowerBuilder functions and events
116
Chapter 6 Calling Functions and Events
117
Calling functions and events in an object’s ancestor
118
Chapter 6 Calling Functions and Events
119
Calling functions and events in an object’s ancestor
120
PART 2 Statements, Events, and
Functions
CH A PTE R 7 PowerScript Statements
About this chapter This chapter describes the PowerScript statements and how to use them in
scripts.
Contents
Topic Page
Assignment 124
CALL 127
CHOOSE CASE 128
CONTINUE 130
CREATE 131
DESTROY 134
DO...LOOP 135
EXIT 138
FOR...NEXT 139
GOTO 141
HALT 142
IF...THEN 143
RETURN 145
THROW 146
THROWS 147
TRY...CATCH...FINALLY...END TRY 149
123
Assignment
Assignment
Description Assigns values to variables or object properties or object references to object
variables.
Syntax variablename = expression
Argument Description
variablename The name of the variable or object property to which you
want to assign a value. Variablename can include dot
notation to qualify the variable with one or more object
names
expression An expression whose data type is compatible with
variablename
124
Chapter 7 PowerScript Statements
Unless you have prohibited the use of dashes in variable names, you must leave
a space before -- and -= (otherwise, PowerScript reads the minus sign as part
of a variable name).
For more information, see "Identifier names" on page 6.
Examples Example 1 These statements each assign a value to the variable ld_date:
date ld_date
ld_date = Today( )
ld_date = 1996-01-01
ld_date = Date("January 1, 1996")
Example 2 This statement assigns the parent of the current control to a
window variable:
window lw_current_window
lw_current_window = Parent
Example 3 This statement makes a CheckBox invisible:
cbk_on.Visible = FALSE
Example 4 This statement is not an assignment—it tests the value of the
string in the SingleLineEdit sle_emp:
IF sle_emp.Text = "N" THEN Open(win_1)
Example 5 These statements concatenate two strings and assigns the value to
the string Text1:
string Text1
Text1 = sle_emp.Text+".DAT"
Operator shortcuts These assignments use operator shortcuts:
int i = 4
i ++ // i is now 5.
i -- // i is 4 again.
i += 10 // i is now 14.
i /= 2 // i is now 7.
125
Assignment
These shortcuts can be used only in pure assignment statements. They cannot
be used with other operators in a statement. For example, the following is
invalid:
int i, j
i = 12
j = i ++ // INVALID
The following is valid, because ++ is used by itself in the assignment:
int i, j
i = 12
i ++
j = i
126
Chapter 7 PowerScript Statements
CALL
Description Calls an ancestor script from a script for a descendent object. You can call
scripts for events in an ancestor of the user object, menu, or window. You can
also call scripts for events for controls in an ancestor of the user object or
window.
When you use the CALL statement to call an ancestor event script, the
AncestorReturnValue variable is generated. For more information on the
AncestorReturnValue variable, see "About events" on page 194.
Syntax CALL ancestorobject {‘ controlname}::event
Parameter Description
ancestorobject An ancestor of the descendent object
controlname The name of a control in an ancestor window or custom
(optional) user object
event An event in the ancestor object
Usage New syntax New syntax for calling functions and events allows you to
trigger or post an event or function in an ancestor and then pass arguments. But
the new syntax does not allow you to call a script for a control in the ancestor.
For more information about the new syntax, see "Calling functions and events
in an object’s ancestor" on page 117.
Super In some circumstances, you can use the pronoun Super when
ancestorobject is the descendant object’s immediate ancestor.See the
discussion of "Super pronoun" on page 17.
Passing arguments If the call is being made to an ancestor event, the
arguments passed to the current event are automatically propagated to the
ancestor event. If you call a non-ancestor event and pass arguments, you need
to use the new syntax, otherwise NULL will be passed for each argument.
Examples Example 1 This statement calls a script for an event in an ancestor window:
CALL w_emp::Open
Example 2 This statement calls a script for an event in a control in an
ancestor window:
CALL w_emp‘cb_close::Clicked
127
CHOOSE CASE
CHOOSE CASE
Description A control structure that directs program execution based on the value of a test
expression (usually a variable).
Syntax CHOOSE CASE testexpression
CASE expressionlist
statementblock
{ CASE expressionlist
statementblock
...
CASE expressionlist
statementblock }
CASE ELSE
statementblock }
END CHOOSE
Parameter Description
testexpression The expression on which you want to base the execution
of the script
expressionlist One of the following expressions:
• A single value
• A list of values separated by commas (such as 2, 4, 6,
8)
• A TO clause (such as 1 TO 30)
• IS followed by a relational operator and comparison
value (such as IS>5)
• Any combination of the above with an implied OR
between expressions (such as 1, 3, 5, 7, 9, 27 TO 33,
IS >42)
statementblock The block of statements you want PowerBuilder to
execute if the test expression matches the value in
expressionlist
Usage At least one CASE clause is required. You must end a CHOOSE CASE control
structure with END CHOOSE.
If testexpression at the beginning of the CHOOSE CASE statement matches a
value in expressionlist for a CASE clause, the statements immediately
following the CASE clause are executed. Control then passes to the first
statement after the END CHOOSE clause.
If multiple CASE expressions exist, then testexpression is compared to each
expressionlist until a match is found or the CASE ELSE or END CHOOSE is
encountered.
128
Chapter 7 PowerScript Statements
If there is a CASE ELSE clause and the test value does not match any of the
expressions, statementblock in the CASE ELSE clause is executed. If no CASE
ELSE clause exists and a match is not found, the first statement after the END
CHOOSE clause is executed.
Examples Example 1 These statements provide different processing based on the value
of the variable Weight:
CHOOSE CASE Weight
CASE IS<16
Postage=Weight*0.30
Method="USPS"
CASE 16 to 48
Postage=4.50
Method="UPS"
CASE ELSE
Postage=25.00
Method="FedEx"
END CHOOSE
Example 2 These statements convert the text in a SingleLineEdit control to a
real value and provide different processing based on its value:
CHOOSE CASE Real(sle_real.Text)
CASE is < 10.99999
sle_message.Text = "Real Case < 10.99999"
CASE 11.00 to 48.99999
sle_message.Text = "Real Case 11 to 48.9999
CASE is > 48.9999
sle_message.Text = "Real Case > 48.9999"
CASE ELSE
sle_message.Text = "Cannot evaluate!"
END CHOOSE
129
CONTINUE
CONTINUE
Description In a DO...LOOP or a FOR...NEXT control structure, skips statements in the
loop. CONTINUE takes no parameters.
Syntax CONTINUE
Usage When PowerBuilder encounters a CONTINUE statement in a DO...LOOP or
FOR...NEXT block, control passes to the next LOOP or NEXT statement. The
statements between the CONTINUE statement and the loop’s end statement
are skipped in the current iteration of the loop. In a nested loop, a CONTINUE
statement bypasses statements in the current loop structure.
For information on how to break out of the loop, see EXIT on page 138.
Examples Example 1 These statements display a message box twice: when B equals 2
and when B equals 3. As soon as B is greater than 3, the statement following
CONTINUE is skipped during each iteration of the loop:
integer A=1, B=1
DO WHILE A < 100
A = A+1
B = B+1
IF B > 3 THEN CONTINUE
MessageBox("Hi", "B is " + String(B) )
LOOP
Example 2 These statements stop incrementing B as soon as Count is greater
than 15:
integer A=0, B=0, Count
FOR Count = 1 to 100
A = A + 1
IF Count > 15 THEN CONTINUE
B = B + 1
NEXT
// Upon completion, a=100 and b=15.
130
Chapter 7 PowerScript Statements
CREATE
Description Creates an object instance for a specified object type. After a CREATE
statement, properties of the created object instance can be referenced using dot
notation.
The CREATE statement returns an object instance which can be stored in a
variable of the same type.
Syntax 1 specifies the object type at compilation. Syntax 2 allows the
application to choose the object type dynamically.
Syntax Syntax 1 (specifies the object type at compilation):
objectvariable = CREATE objecttype
Parameter Description
objectvariable A global, instance, or local variable whose data type
is objecttype
objecttype The object data type
Parameter Description
objectvariable A global, instance, or local variable whose data type
is the same class as the object being created or an
ancestor of that class
objecttypestring A string whose value is the name of the class data
type to be created
Usage Use CREATE as the first reference to any Class user object. This includes
standard Class user objects such as mailSession or Transaction.
The system provides one instance of several standard Class user objects:
Message, Error, Transaction, DynamicDescriptionArea, and
DynamicStagingArea. You only need to use CREATE if you declare additional
instances of these objects.
If you need a menu that is not part of an open window definition, use CREATE
to create an instance of the menu. (See the function PopMenu on page 874.)
To create an instance of a visual user object or window, use the appropriate
Open function (instead of CREATE).
You do not need to use CREATE to allocate memory for:
• A standard data type, such as integer or string
131
CREATE
IF ... THEN
ls_objectname = "uo_a_desc1"
ELSE
ls_objectname = "uo_a_desc2"
END IF
uo_a_var = CREATE USING ls_objectname
Destroying objects you create When you are finished with an object you
created, you can call DESTROY to release its memory.However, you should
only call DESTROY if you are sure that the object is not referenced by any
other object. PowerBuilder’s garbage collection mechanism maintains a count
of references to each object and destroys unreferenced objects automatically.
For more information about garbage collection, see Application Techniques.
Examples Example 1 These statements create a new transaction object and stores the
object in the variable DBTrans:
transaction DBTrans
DBTrans = CREATE transaction
DBTrans.DBMS = ’ODBC’
Example 2 These statements create a user object when the application has
need of the services it provides. Because the user object may or may not exist,
the code that accesses it checks whether it exists before calling its functions.
The object that creates the service object declares invo_service as an instance
variable:
n_service invo_service
132
Chapter 7 PowerScript Statements
The Open event for the object creates the service object:
//Open event of some object
IF (some condition) THEN
invo_service = CREATE n_service
END IF
When another script wants to call a function that belongs to the n_service class,
it checks that invo_service is instantiated:
IF IsValid(invo_service) THEN
invo_service.of_perform_some_work( )
END IF
If the service object was created, then it also needs to be destroyed:
IF isvalid(invo_service) THEN DESTROY invo_service
Example 3 When you create a DataStore object, you also have to give it a
DataObject and call SetTransObject before you can use it:
l_ds_delete = CREATE u_ds
l_ds_delete.DataObject = ’d_user_delete’
l_ds_delete.SetTransObject(SQLCA)
li_cnt = l_ds_delete.Retrieve(lstr_data.name)
Example 4 In this example, n_file_service_class is an ancestor object and
n_file_service_class_ansi and n_file_service_class_dbcs are its descendants.
They hold functions and variables that provide services for the application. The
code chooses which object to create based on whether the user is running in a
DBCS environment:
n_file_service_class lnv_fileservice
string ls_objectname
environment luo_env
GetEnvironment ( luo_env )
IF luo_env.charset = charsetdbcs! THEN
ls_objectname = "n_file_service_class_dbcs"
ELSE
ls_objectname = "n_file_service_class_ansi"
END IF
133
DESTROY
DESTROY
Description Eliminates an object instance that was created with the CREATE statement.
After a DESTROY statement, properties of the deleted object instance can no
longer be referenced.
Syntax DESTROY objectvariable
Parameter Description
objectvariable A variable whose data type is a PowerBuilder object
Usage When you are finished with an object that you created, you can call DESTROY
to release its memory. However, you should only call DESTROY if you are
sure that the object is not referenced by any other object. PowerBuilder’s
garbage collection mechanism maintains a count of references to each object
and destroys unreferenced objects automatically.
For more information about garbage collection, see Application Techniques.
All objects are destroyed automatically when your application terminates.
Examples Example 1 The following statement destroys the transaction object DBTrans
that was created with a CREATE statement:
DESTROY DBTrans
Example 2 This example creates an OLEStorage variable istg_prod_pic in a
window’s Open event. When the window is closed, the Close event script
destroys the object.The variable’s declaration is:
OLEStorage istg_prod_pic
The window’s Open event creates an object instance and opens an OLE storage
file:
integer li_result
istg_prod_pic = CREATE OLEStorage
li_result = stg_prod_pic.Open("PICTURES.OLE")
The window’s Close event destroys istg_prod_pic:
integer li_result
li_result = istg_prod_pic.Save( )
IF li_result = 0 THEN
DESTROY istg_prod_pic
END IF
134
Chapter 7 PowerScript Statements
DO...LOOP
Description A control structure that is a general-purpose iteration statement used to execute
a block of statements while or until a condition is true.
DO... LOOP has four formats:
• DO UNTIL Executes a block of statements until the specified condition
is TRUE. If the condition is TRUE on the first evaluation, the statement
block does not execute.
• DO WHILE Executes a block of statements while the specified condition
is TRUE. The loop ends when the condition becomes FALSE. If the
condition is FALSE on the first evaluation, the statement block does not
execute.
• LOOP UNTIL Executes a block of statements at least once and continues
until the specified condition is TRUE.
• LOOP WHILE Executes a block of statements at least once and continues
while the specified condition is TRUE. The loop ends when the condition
becomes FALSE.
In all four formats of the DO...LOOP control structure, DO marks the
beginning of the statement block that you want to repeat. The LOOP statement
marks the end.
You can nest DO...LOOP control structures.
Syntax DO UNTIL condition
statementblock
LOOP
Parameter Description
condition The condition you are testing
statementblock The block of statements you want to repeat
DO WHILE condition
statementblock
LOOP
Parameter Description
condition The condition you are testing
statementblock The block of statements you want to repeat
135
DO...LOOP
DO
statementblock
LOOP UNTIL condition
Parameter Description
statementblock The block of statements you want to repeat
condition The condition you are testing
DO
statementblock
LOOP WHILE condition
Parameter Description
statementblock The block of statements you want to repeat
condition The condition you are testing
136
Chapter 7 PowerScript Statements
LOOP UNTIL The following LOOP UNTIL executes the Beep function and
then continues to execute the function until A is greater than 1:
integer A = 1, B = 1
DO
Beep(A)
A = (A + 1) * B
LOOP UNTIL A > 15
LOOP WHILE The following LOOP WHILE repeatedly executes the Beep
function while A is less than or equal to 15:
integer A = 1, B = 1
DO
Beep(A)
A = (A + 1) * B
LOOP WHILE A <= 15
137
EXIT
EXIT
Description In a DO...LOOP or a FOR...NEXT control structure, passes control out of the
current loop. EXIT takes no parameters.
Syntax EXIT
Usage An EXIT statement in a DO...LOOP or FOR...NEXT control structure causes
control to pass to the statement following the LOOP or NEXT statement. In a
nested loop, an EXIT statement passes control out of the current loop structure.
For information on how to jump to the end of the loop and continue looping,
see CONTINUE on page 130.
Examples Example 1 This EXIT statement causes the loop to terminate if an element in
the Nbr array equals 0:
int Nbr[10]
int Count = 1
// Assume values get assigned to Nbr array...
DO WHILE Count < 11
IF Nbr[Count] = 0 THEN EXIT
Count = Count + 1
LOOP
MessageBox("Hi", "Count is now " + String(Count) )
Example 2 This EXIT statement causes the loop to terminate if an element in
the Nbr array equals 0:
int Nbr[10]
int Count
// Assume values get assigned to Nbr array...
FOR Count = 1 to 10
IF Nbr[Count] = 0 THEN EXIT
NEXT
MessageBox("Hi", "Count is now " + String(Count) )
138
Chapter 7 PowerScript Statements
FOR...NEXT
Description A control structure that is a numerical iteration, used to execute one or more
statements a specified number of times.
Syntax FOR varname = start TO end {STEP increment}
statementblock
NEXT
Parameter Description
varname The name of the iteration counter variable. It can be any
numerical type (integer, double, real, long, or decimal),
but integers provide the fastest performance
start Starting value of varname
end Ending value of varname
increment The increment value. Increment must be a constant and
(optional) the same data type as varname. If you enter an increment,
STEP is required. +1 is the default increment
statementblock The block of statements you want to repeat
Usage Using the start and end parameters For a positive increment, end must be
greater than start. For a negative increment, end must be less than start.
When increment is positive and start is greater than end, statementblock does
not execute. When increment is negative and start is less than end,
statementblock does not execute.
When start and end are expressions, they are reevaluated on each pass through
the loop. So if the expression’s value changes, it will affect the number of
loops. Consider this example—the body of the loop changes the number of
rows, which changes the result of the RowCount function:
FOR n = 1 TO dw_1.RowCount( )
dw_1.DeleteRow(1)
NEXT
Nesting You can nest FOR...NEXT statements. You must have a NEXT for
each FOR.
You can end the FOR loop with the keywords END FOR instead of NEXT.
139
FOR...NEXT
Avoid overflow
If start or end is too large for the data type of varname, varname will overflow,
which could create an infinite loop. Consider this statement for the integer
li_int.
FOR li_int = 1 TO 50000
The end value 50000 is too large for an integer. When li_int is incremented, it
overflows to a negative value before reaching 50000, creating an infinite loop.
140
Chapter 7 PowerScript Statements
GOTO
Description Transfers control from one statement in a script to another statement that is
labeled.
Syntax GOTO label
Parameter Description
label The label associated with the statement to which you
want to transfer control. A label is an identifier followed
by a colon (such as OK:). Do not use the colon with a
label in the GOTO statement
Examples Example 1 This GOTO statement skips over the Taxable=FALSE line:
Goto NextStep
Taxable=FALSE //This statement will never
//execute.
NextStep:
Rate=Count/Count4
Example 2 This GOTO statement transfers control to the statement
associated with the label OK:
GOTO OK
.
.
.
OK:
.
.
.
141
HALT
HALT
Description Terminates an application.
Syntax HALT {CLOSE}
Usage When PowerBuilder encounters Halt without the keyword CLOSE, it
immediately terminates the application.
When PowerBuilder encounters Halt with the keyword CLOSE, it immediately
executes the script for the Close event for the application and then terminates
the application. If there is no script for the Close event at the application level,
PowerBuilder immediately terminates the application.
Examples Example 1 This statement stops the application if the user enters a password
in the SingleLineEdit named sle_password that does not match the value stored
in a string named CorrectPassword:
IF sle_password.Text <> CorrectPassword THEN HALT
Example 2 This statement executes the script for the Close event for the
application before it terminates the application if the user enters a password in
sle_password that does not match the value stored in the string
CorrectPassword:
IF sle_password.Text <> CorrectPassword &
THEN HALT CLOSE
142
Chapter 7 PowerScript Statements
IF...THEN
Description A control structure used to cause a script to perform a specified action if a
stated condition is true. Syntax 1 uses a single-line format and Syntax 2 uses a
multiline format.
Syntax Syntax 1 (the single-line format):
IF condition THEN action1 {ELSE action2}
Parameter Description
condition The condition you want to test
action1 The action you want performed if the condition is TRUE.
The action must be a single statement on the same line as
the rest of the IF statement
action2 The action you want performed if the condition is
(optional) FALSE. The action must be a single statement on the
same line as the rest of the IF statement
Parameter Description
condition1 The first condition you want to test
action1 The action you want performed if condition1 is TRUE.
The action can be a statement or multiple statements that
are separated by semicolons or placed on separate lines.
At least one action is required
condition2 The condition you want to test if condition1 is FALSE.
(optional) You can have multiple ELSEIF...THEN statements in an
IF...THEN control structure
action2 The action you want performed if condition2 is TRUE.
The action can be a statement or multiple statements that
are separated by semicolons or placed on separate lines
action3 The action you want performed if none of the preceding
(optional) conditions is true. The action can be a statement or
multiple statements that are separated by semicolons or
placed on separate lines
143
IF...THEN
Usage You can use continuation characters to place the single-line format on more
than one physical line in the script.
You must end a multiline IF...THEN control structure with END IF (which is
two words).
Examples Example 1 This single-line IF...THEN statement opens window w_first if
Num = 1; otherwise, w_rest is opened:
IF Num = 1 THEN Open(w_first) ELSE Open(w_rest)
Example 2 This single-line IF...THEN statement displays a message if the
value in the SingleLineEdit sle_State is TX. It uses the continuation character
to continue the single-line statement across two physical lines in the script:
IF sle_State.text="TX" THEN &
MessageBox("Hello","Tex")
Example 3 This multiline IF...THEN compares the horizontal positions of
windows w_first and w_second. If w_first is to the right of w_second, w_first
is moved to the left side of the screen:
IF w_first.X > w_second.X THEN
w_first.X = 0
END IF
Example 4 This multiline IF...THEN causes the application to:
• Beep twice if X equals Y
• Display the Parts listbox and highlight item 5 if X equals Z
• Display the Choose listbox if X is blank
• Hide the Empty button and display the Full button if none of the above
conditions is TRUE
IF X=Y THEN
Beep(2)
ELSEIF X=Z THEN
Show (lb_parts); lb_parts.SetState(5,TRUE)
ELSEIF X=" " THEN
Show (lb_choose)
ELSE
Hide(cb_empty)
Show(cb_full)
END IF
144
Chapter 7 PowerScript Statements
RETURN
Description Stops the execution of a script or function immediately.
Syntax RETURN { expression }
Parameter Description
expression In a function, any value (or expression) you want the
function to return. The return value must be the data type
specified as the return type in the function
Usage When a user’s action triggers an event and PowerBuilder encounters RETURN
in the event script, it terminates execution of that script immediately and waits
for the next user action.
When a script calls a function or event and PowerBuilder encounters RETURN
in the code, RETURN transfers (returns) control to the point at which the
function or event was called.
Examples Example 1 This script causes the system to beep once; the second beep
statement will not execute:
Beep(1)
RETURN
Beep(1) // This statement will not execute.
Example 2 These statements in a user-defined function return the result of
dividing Arg1 by Arg2 if Arg2 is not equal to zero; they return -1 if Arg2 is
equal to zero:
IF Arg2 <> 0 THEN
RETURN Arg1/Arg2
ELSE
RETURN -1
END IF
145
THROW
THROW
Description Used to manually trigger exception handling for user-defined exceptions.
Syntax THROW exlvalue
Parameter Description
exlvalue Variable (or expression that evaluates to a valid instance of an
object) of type Throwable. Usually the object type thrown is a
user-defined exception class derived from the system Exception
class that inherits from Throwable
Usage The variable following the THROW reserved word must be a valid object
instance or an expression that produces a valid object instance that derives
from the Throwable data type. For example, you can use an expression such as:
THROW create ExceptionType
where ExceptionType is an object of type Throwable.
If you attempt to throw a noninstantiated exception, you will not get back the
exception information you want, since the only exception information you
retrieve will be a NullObjectError.
In a method script, you can only throw an exception that you declare in the
method prototype or that you handle in a TRY-CATCH block. The PowerScript
compiler displays an error message if you try to throw a user-defined exception
without declaring it in the prototype Throws statement and without
surrounding it in an appropriate TRY-CATCH block.
When a RuntimeError—or a descendant of RuntimeError—is thrown, the
instance variable containing line number information will be filled in at the
point where the THROW statement occurs. If the error is handled and thrown
again, this information will not be updated unless it has specifically been set to
NULL.
Examples long ll_result
ll_result = myConnection.ConnectToServer()
146
Chapter 7 PowerScript Statements
THROWS
Description Used to declare the type of exception that a method triggers. It is part of the
method prototype.
Syntax methodname ( {arguments} ) THROWS ExceptionType { , ExceptionType, ... }
Parameter Description
methodname Name of the method that throws an exception
arguments Arguments of the method that throws an exception. Depending
on the method, the method arguments can be optional
ExceptionType Object of type Throwable. Usually the object type thrown is a
user-defined exception class derived from the system Exception
class. If you define multiple potential exceptions for a method,
you can throw each type of exception in the same clause by
separating the exception types with commas
147
THROWS
The exceptions you add to the THROWS clause are usually checked
exceptions. The PowerBuilder compiler checks whether a user-defined
exception thrown on a method call in a script matches an exception in the
THROWS clause for that method. PowerBuilder automatically adds the
RuntimeError object and its descendents to the THROWS clause of all
methods, so it is not necessary to add them yourself.
If you select a high-level exception or error type for the THROWS clause of a
given method, you can throw any lower-level exception or error in the method
script, but in that case you risk hiding any useful information obtainable from
the lower-level exception or error.
148
Chapter 7 PowerScript Statements
TRY...CATCH...FINALLY...END TRY
Description Isolates code that can cause an exception, describes what to do if an exception
of a given type is encountered, and allows you to close files or network
connections (and return objects to their original state) whether or not an
exception is encountered.
Syntax TRY
statementClauseT
{ CATCH ( ThrowableType exIdentifier )
statementClauseC }
{ ... }
{ FINALLY
statementClauseF }
END TRY
Parameter Description
statementClauseT Block of code that might potentially throw an exception
ThrowableType Object type of exception or error to be caught. The CATCH
clause is optional, but for every CATCH clause in a TRY
block you must include a corresponding exception object
type and a local variable of that type
exIdentifier Local variable of type ThrowableType
statementClauseC Code to handle the exception being caught
statementClauseF Cleanup code. The FINALLY clause, like the CATCH
clause, is optional—although you cannot code a TRY block
without either a CATCH clause or a FINALLY clause
The TRY block is used to isolate code that might potentially throw an
exception. The statements between the TRY and CATCH keywords (or the
TRY and FINALLY keywords if there is no CATCH clause) are run
unconditionally until either the entire block of statements is executed or some
statement in the block causes an exception to be thrown.
149
TRY...CATCH...FINALLY...END TRY
150
CH A PTE R 8 SQL Statements
About this chapter This chapter describes the embedded SQL and dynamic SQL statements
and how to use them in scripts.
Contents
Topic Page
Using SQL in scripts 152
CLOSE Cursor 155
CLOSE Procedure 156
COMMIT 157
CONNECT 158
DECLARE Cursor 159
DECLARE Procedure 160
DELETE 162
DELETE Where Current of Cursor 163
DISCONNECT 164
EXECUTE 165
FETCH 166
INSERT 167
OPEN Cursor 168
ROLLBACK 169
SELECT 170
SELECTBLOB 172
UPDATE 174
UPDATEBLOB 175
UPDATE Where Current of Cursor 177
Using dynamic SQL 178
Dynamic SQL Format 1 182
Dynamic SQL Format 2 183
Dynamic SQL Format 3 185
Dynamic SQL Format 4 188
151
Using SQL in scripts
152
Chapter 8 SQL Statements
Error reporting
Not all DBMSs return a conversion error when the data type of a column does
not match the data type of the associated variable.
The following statement uses the indicator variable IndVar2 to see if Address
contains a NULL value:
if IndVar2 = -1 then...
You could also use the PowerScript IsNull function to accomplish the same
result without using indicator variables:
if IsNull( Address ) then ...
This statement uses the indicator variable IndVar3 to set City to NULL:
IndVar3 = -1
You could also use the PowerScript SetNull function to accomplish the same
result without using indicator variables:
SetNull( City )
For information about the SetNull function, see SetNull on page 1084.
Error handling in The scripts shown in the SQL examples above do not include error handling,
scripts but it is good practice to test the success and failure codes (the SQLCode
attribute) in the transaction object after every statement. The codes are:
Value Meaning
0 Success
100 Fetched row not found
-1 Error; the statement failed. Use SQLErrText or SQLDBCode to obtain
the detail.
After certain statements such as DELETE, FETCH, and UPDATE, you should
also check the SQLNRows property of the transaction object to make sure the
action affected at least one row.
About SQLErrText and SQLDBCode The string SQLErrText in the
transaction object contains the database vendor–supplied error message. The
long named SQLDBCode in the transaction object contains the database
vendor–supplied status code:
IF SQLCA.SQLCode = -1 THEN
MessageBox("SQL error", SQLCA.SQLErrText)
END IF
153
Using SQL in scripts
Painting standard You can paint the following SQL statements in scripts and functions:
SQL
• Declarations of SQL cursors and stored procedures
• Cursor FETCH, UPDATE, and DELETE statements
• Noncursor SELECT, INSERT, UPDATE, and DELETE statements
For more information about scope, see "Where to declare variables" on page
36.
You can declare cursors and stored procedures at the scope of global, instance,
shared, or local variables. A cursor or procedure can be declared in the Script
view using the Paste SQL button in the PainterBar.
You can paint standard embedded SQL statements in the Script view, the
Function painter, and the Interactive SQL view in the Database painter using
the Paste SQL button in the PainterBar or the Paste Special>SQL item from the
popup menu.
Supported SQL In general, all DBMS-specific features are supported in PowerScript as long as
statements they occur within a PowerScript-supported SQL statement. For example,
PowerScript supports DBMS-specific built-in functions within a SELECT
command.
154
Chapter 8 SQL Statements
CLOSE Cursor
Description Closes the SQL cursor CursorName; ends processing of CursorName.
Syntax CLOSE CursorName ;
Parameter Description
CursorName The cursor you want to close
Usage This statement must be preceded by an OPEN statement for the same cursor.
The USING TransactionObject clause is not allowed with CLOSE; the
transaction object was specified in the statement that declared the cursor.
CLOSE often appears in the script that is executed when the SQL code after a
fetch equals 100 (not found).
Error handling
It is good practice to test the success/failure code after executing a CLOSE
Cursor statement.
155
CLOSE Procedure
CLOSE Procedure
Description Closes the SQL procedure ProcedureName; ends processing of
ProcedureName.
DBMS-specific
Not all DBMSs support stored procedures.
Usage This statement must be preceded by an EXECUTE statement for the same
procedure. The USING TransactionObject clause is not allowed with CLOSE;
the transaction object was specified in the statement that declared the
procedure.
You only need to use CLOSE to close procedures that return result sets.
PowerBuilder automatically closes procedures that don’t return result sets (and
sets the return code to 100).
CLOSE often appears in the script that is executed when the SQL code after a
fetch equals 100 (not found).
Error handling
It is good practice to test the success/failure code after executing a CLOSE
Procedure statement.
156
Chapter 8 SQL Statements
COMMIT
Description Permanently updates all database operations since the previous COMMIT,
ROLLBACK, or CONNECT for the specified transaction object.
Usage COMMIT does not cause a disconnect, but it does close all open cursors or
procedures. (But note that the DISCONNECT statement in PowerBuilder does
issue a COMMIT.)
Error handling
It is good practice to test the success/failure code after executing a COMMIT
statement.
Examples Example 1 This statement commits all operations for the database specified
in the default transaction object:
COMMIT ;
Example 2 This statement commits all operations for the database specified
in the transaction object named Emp_tran:
COMMIT USING Emp_tran ;
157
CONNECT
CONNECT
Description Connects to a specified database.
Syntax CONNECT {USING TransactionObject} ;
Parameter Description
TransactionObject The name of the transaction object containing the
required connection information for the database to
which you want to connect. This clause is required only
for transaction objects other than the default (SQLCA)
Usage This statement must be executed before any actions (such as INSERT,
UPDATE, or DELETE) can be processed using the default transaction object
or the specified transaction object.
Error handling
It is good practice to test the success/failure code after executing a CONNECT
statement.
Examples Example 1 This statement connects to the database specified in the default
transaction object:
CONNECT ;
Example 2 This statement connects to the database specified in the
transaction object named Emp_tran:
CONNECT USING Emp_tran ;
158
Chapter 8 SQL Statements
DECLARE Cursor
Description Declares a cursor for the specified transaction object.
Syntax DECLARE CursorName CURSOR FOR SelectStatement
{USING TransactionObject} ;
Parameter Description
CursorName Any valid PowerBuilder name
SelectStatement Any valid SELECT statement
TransactionObject The name of the transaction object for which you want to
declare the cursor. This clause is required only for
transaction objects other than the default (SQLCA)
159
DECLARE Procedure
DECLARE Procedure
Description Declares a procedure for the specified transaction object.
DBMS-specific
Not all DBMSs support stored procedures.
160
Chapter 8 SQL Statements
161
DELETE
DELETE
Description Deletes the rows in TableName specified by Criteria.
Syntax DELETE FROM TableName WHERE Criteria {USING TransactionObject} ;
Parameter Description
TableName The name of the table from which you want to delete
rows
Criteria Criteria that specify which rows to delete
TransactionObject The name of the transaction object that identifies the
database containing the table. This clause is required
only for transaction objects other than the default
(SQLCA)
Examples Example 1 This statement deletes rows from the Employee table in the
database specified in the default transaction object where Emp_num is less
than 100:
DELETE FROM Employee WHERE Emp_num < 100 ;
Example 2 These statements delete rows from the Employee table in the
database named in the transaction object named Emp_tran where Emp_num is
equal to the value entered in the SingleLineEdit sle_number:
int Emp_num
Emp_num = Integer(sle_number.Text)
DELETE FROM Employee
WHERE Employee.Emp_num = :Emp_num ;
The integer Emp_num requires a colon in front of it to indicate it is a variable
when it is used in a WHERE clause.
162
Chapter 8 SQL Statements
DBMS-specific
Not all DBMSs support DELETE Where Current of Cursor.
Usage The USING TransactionObject clause is not allowed with this form of
DELETE Where Current of Cursor; the transaction object was specified in the
statement that declared the cursor.
Error handling
It is good practice to test the success/failure code after executing a DELETE
Where Current of Cursor statement.
Examples This statement deletes from the Employee table the row in which the cursor
named Emp_cur is positioned:
DELETE FROM Employee WHERE current of Emp_curs ;
163
DISCONNECT
DISCONNECT
Description Executes a COMMIT for the specified transaction object and then disconnects
from the specified database.
Syntax DISCONNECT {USING TransactionObject} ;
Parameter Description
TransactionObject The name of the transaction object that identifies the
database you want to disconnect from and in which you
want to permanently update all database operations since
the previous COMMIT, ROLLBACK, or CONNECT.
This clause is required only for transaction objects other
than the default (SQLCA)
Examples Example 1 This statement disconnects from the database specified in the
default transaction object:
DISCONNECT ;
Example 2 This statement disconnects from the database specified in the
transaction object named Emp_tran:
DISCONNECT USING Emp_tran ;
164
Chapter 8 SQL Statements
EXECUTE
Description Executes the previously declared procedure identified by ProcedureName.
Syntax EXECUTE ProcedureName ;
Parameter Description
ProcedureName The name assigned in the DECLARE statement of the
stored procedure you want to execute. The procedure
must have been declared previously. ProcedureName is
not necessarily the name of the procedure stored in the
database
Usage The USING TransactionObject clause is not allowed with EXECUTE; the
transaction object was specified in the statement that declared the procedure.
Error handling
It is good practice to test the success/failure code after executing an EXECUTE
statement.
165
FETCH
FETCH
Description Fetches the row after the row on which Cursor | Procedure is positioned.
Syntax FETCH Cursor | Procedure INTO HostVariableList ;
Parameter Description
Cursor or Procedure The name of the cursor or procedure from which you
want to fetch a row
HostVariableList PowerScript variables into which data values will be
retrieved
Usage The USING TransactionObject clause is not allowed with FETCH; the
transaction object was specified in the statement that declared the cursor or
procedure.
If your DBMS supports formats of FETCH other than the customary (and
default) FETCH NEXT, you can specify FETCH FIRST, FETCH PRIOR, or
FETCH LAST.
Error handling
It is good practice to test the success/failure code after executing a FETCH
statement. To see if the FETCH was successful, you can test SLQCode for a
failure code. However, if nothing matches the WHERE clause and no rows are
fetched, SQLCode is still set to 100. To make sure the fetch affected at least
one row, check the SQLNRows property of the transaction object.
Examples Example 1 This statement fetches data retrieved by the SELECT clause in
the declaration of the cursor named Emp_cur and puts it into Emp_num and
Emp_name:
int Emp_num
string Emp_name
FETCH Emp_cur INTO :Emp_num, :Emp_name ;
Example 2 If sle_emp_num and sle_emp_name are SingleLineEdits, these
statements fetch from the cursor named Emp_cur, store the data in Emp_num
and Emp_name, and then convert Emp_num from an integer to a string, and
put them in sle_emp_num and sle_emp_name:
int Emp_num
string Emp_name
FETCH Emp_cur INTO :emp_num, :emp_name ;
sle_emp_num.Text = string(Emp_num)
sle_emp_name.Text = Emp_name
166
Chapter 8 SQL Statements
INSERT
Description Inserts one or more new rows into the table specified in RestOfInsertStatement.
Syntax INSERT RestOfInsertStatement
{USING TransactionObject} ;
Parameter Description
RestOfInsertStatement The rest of the INSERT statement (the INTO clause,
list of columns and values or source)
TransactionObject The name of the transaction object that identifies the
database containing the table. This clause is required
only for transaction objects other than the default
(SQLCA)
Examples Example 1 These statements insert a row with the values in EmpNbr and
EmpName into the Emp_nbr and Emp_name columns of the Employee table
identified in the default transaction object:
int EmpNbr
string EmpName
...
INSERT INTO Employee (employee.Emp_nbr,
employee.Emp_name)
VALUES (:EmpNbr, :EmpName) ;
Example 2 These statements insert a row with the values entered in the
SingleLineEdits sle_number and sle_name into the Emp_nbr and Emp_name
columns of the Employee table in the transaction object named Emp_tran:
int EmpNbr
string EmpName
EmpNbr = Integer(sle_number.Text)
EmpName = sle_name.Text
INSERT INTO Employee (employee.Emp_nbr,
employee.Emp_name)
VALUES (:EmpNbr, :EmpName) USING Emp_tran ;
167
OPEN Cursor
OPEN Cursor
Description Causes the SELECT specified when the cursor was declared to be executed.
Syntax OPEN CursorName ;
Parameter Description
CursorName The name of the cursor you want to open
Usage The USING TransactionObject clause is not allowed with OPEN; the
transaction object was specified in the statement that declared the cursor.
Error handling
It is good practice to test the success/failure code after executing an OPEN
Cursor statement.
168
Chapter 8 SQL Statements
ROLLBACK
Description Cancels all database operations in the specified database since the last
COMMIT, ROLLBACK, or CONNECT.
Usage ROLLBACK does not cause a disconnect, but it does close all open cursors and
procedures.
Error handling
It is good practice to test the success/failure code after executing a
ROLLBACK statement.
Examples Example 1 This statement cancels all database operations in the database
specified in the default transaction object:
ROLLBACK ;
Example 2 This statement cancels all database operations in the database
specified in the transaction object named Emp_tran:
ROLLBACK USING emp_tran ;
169
SELECT
SELECT
Description Selects a row in the tables specified in RestOfSelectStatement.
Syntax SELECT RestOfSelectStatement
{USING TransactionObject} ;
Parameter Description
RestOfSelectStatement The rest of the SELECT statement (the column list
INTO, FROM, WHERE, and other clauses)
TransactionObject The name of the transaction object that identifies the
database containing the table. This clause is required
only for transaction objects other than the default
(SQLCA)
Usage An error occurs if the SELECT statement returns more than one row.
Error handling
It is good practice to test the success/failure code after executing a SELECT
statement. You can test SQLCode for a failure code.
When you use the INTO clause, PowerBuilder does not verify whether the data
type of the retrieved column matches the data type of the host variable. It only
checks for the existence of the columns and tables. You are responsible for
checking that the data types match. Keep in mind that not all database data
types are the same as PowerBuilder data types.
Examples The following statements select data in the Emp_LName and Emp_FName
columns of a row in the Employee table and put the data into the
SingleLineEdits sle_LName and sle_FName (the transaction object Emp_tran
is used):
int Emp_num
string Emp_lname, Emp_fname
Emp_num = Integer(sle_Emp_Num.Text)
170
Chapter 8 SQL Statements
171
SELECTBLOB
SELECTBLOB
Description Selects a single blob column in a row in the table specified in
RestOfSelectStatement.
Syntax SELECTBLOB RestOfSelectStatement
{USING TransactionObject} ;
Parameter Description
RestOfSelectStatement The rest of the SELECT statement (the INTO,
FROM, and WHERE clauses)
TransactionObject The name of the transaction object that identifies the
database containing the table. This clause is required
only for transaction objects other than the default
(SQLCA)
Usage An error occurs if the SELECTBLOB statement returns more than one row.
Error handling
It is good practice to test the success/failure code after executing an
SELECTBLOB statement. To make sure the update affected at least one row,
check the SQLNRows property of SQLCA or the transaction object. The
SQLCode or SQLDBCode property will not indicate the success or failure of
the SELECTBLOB statement.
You can include an indicator variable in the host variable list (target
parameters) in the INTO clause to check for an empty blob (a blob of zero
length) and conversion errors.
Database information
Sybase ASE and Microsoft SQL Server users must set the AutoCommit
property of the transaction object to True before calling the SELECTBLOB
function.
For information about the AutoCommit property, see Connecting to Your
Database.
Examples The following statements select the blob column Emp_pic from a row in the
Employee table and set the picture p_1 to the bitmap in Emp_id_pic (the
transaction object Emp_tran is used):
Blob Emp_id_pic
SELECTBLOB Emp_pic
INTO :Emp_id_pic
172
Chapter 8 SQL Statements
FROM Employee
WHERE Employee.Emp_Num = 100
USING Emp_tran ;
p_1.SetPicture(Emp_id_pic)
The blob Emp_id_pic requires a colon to indicate it is a host (PowerScript)
variable when you use it in the INTO clause of the SELECTBLOB statement.
173
UPDATE
UPDATE
Description Updates the rows specified in RestOfUpdateStatement.
Syntax UPDATE TableName RestOfUpdateStatement {USING TransactionObject} ;
Parameter Description
TableName The name of the table in which you want to update
rows
RestOfUpdateStatement The rest of the UPDATE statement (the SET and
WHERE clauses)
TransactionObject The name of the transaction object that identifies the
database containing the table. This clause is required
only for transaction objects other than the default
(SQLCA)
Examples These statements update rows from the Employee table in the database
specified in the transaction object named Emp_tran where Emp_num is equal
to the value entered in the SingleLineEdit sle_Number:
int Emp_num
Emp_num=Integer(sle_Number.Text )
UPDATE Employee
SET emp_name = :sle_Name.Text
WHERE Employee.emp_num = :Emp_num
USING Emp_tran ;
174
Chapter 8 SQL Statements
UPDATEBLOB
Description Updates the rows in TableName in BlobColumn.
Syntax UPDATEBLOB TableName
SET BlobColumn = BlobVariable
RestOfUpdateStatement {USING TransactionObject} ;
Parameter Description
TableName The name of the table you want to update
BlobColumn The name of the column you want to update in
TableName. The data type of this column must be
blob
BlobVariable A PowerScript variable of the data type blob
RestOfUpdateStatement The rest of the UPDATE statement (the WHERE
clause)
TransactionObject The name of the transaction object that identifies the
database containing the table. This clause is
required only for transaction objects other than the
default (SQLCA)
Database information
Sybase ASE and Microsoft SQL Server users must set the AutoCommit
property of the transaction object to True before calling the UPDATEBLOB
function.
For information about the AutoCommit property, see Connecting to Your
Database.
Examples These statements update the blob column emp_pic in the Employee table
where emp_num is 100:
int fh
blob Emp_id_pic
fh = FileOpen("c:\emp_100.bmp", StreamMode!)
IF fh <> -1 THEN
FileRead(fh, emp_id_pic)
175
UPDATEBLOB
FileClose(fh)
UPDATEBLOB Employee SET emp_pic = :Emp_id_pic
WHERE Emp_num = 100
USING Emp_tran ;
END IF
176
Chapter 8 SQL Statements
Usage The USING Transaction Object clause is not allowed with UPDATE Where
Current of Cursor; the transaction object was specified in the statement that
declared the cursor.
Examples This statement updates the row in the Employee table in which the cursor
called Emp_curs is positioned:
UPDATE Employee
SET salary = 17800
WHERE CURRENT of Emp_curs ;
177
Using dynamic SQL
Four formats PowerBuilder has four dynamic SQL formats. Each format handles one of the
following situations at compile time:
Format When used
Format 1 Non-result-set statements with no input parameters
Format 2 Non-result-set statements with input parameters
Format 3 Result-set statements in which the input parameters and result-set
columns are known at compile time
Format 4 Result-set statements in which the input parameters, the result-set
columns or both are unknown at compile time
178
Chapter 8 SQL Statements
DESCRIBE DynamicStagingArea
INTO DynamicDescriptionArea ;
EXECUTE {IMMEDIATE} SQLStatement
{USING TransactionObject} ;
EXECUTE DynamicStagingArea
USING ParameterList ;
EXECUTE DYNAMIC Cursor | Procedure
USING ParameterList ;
OPEN DYNAMIC Cursor | Procedure
USING ParameterList ;
EXECUTE DYNAMIC Cursor | Procedure
USING DESCRIPTOR DynamicDescriptionArea ;
OPEN DYNAMIC Cursor | Procedure
USING DESCRIPTOR DynamicDescriptionArea ;
PREPARE DynamicStagingArea
FROM SQLStatement {USING TransactionObject} ;
Two data types DynamicStagingArea DynamicStagingArea is a PowerBuilder data type.
PowerBuilder uses a variable of this type to store information for use in
subsequent statements.
The DynamicStagingArea is the only connection between the execution of a
statement and a transaction object and is used internally by PowerBuilder; you
cannot access information in the DynamicStagingArea.
PowerBuilder provides a global DynamicStagingArea variable named SQLSA
that you can use when you need a DynamicStagingArea variable.
If necessary, you can declare and create additional object variables of the type
DynamicStagingArea. These statements declare and create the variable, which
must be done before referring to it in a dynamic SQL statement:
DynamicStagingArea dsa_stage1
dsa_stage1 = CREATE DynamicStagingArea
After the EXECUTE statement is completed, SQLSA is no longer referenced.
DynamicDescriptionArea DynamicDescriptionArea is a PowerBuilder data
type. PowerBuilder uses a variable of this type to store information about the
input and output parameters used in Format 4 of dynamic SQL.
PowerBuilder provides a global DynamicDescriptionArea named SQLDA that
you can use when you need a DynamicDescriptionArea variable.
If necessary, you can declare and create additional object variables of the type
DynamicDescriptionArea. These statements declare and create the variable,
which must be done before referring to it in a dynamic SQL statement:
179
Using dynamic SQL
DynamicDescriptionArea dda_desc1
dsa_desc1 = CREATE DynamicDescriptionArea
For more information about SQLDA, see Dynamic SQL Format 4 on page 188.
Preparing to use When you use dynamic SQL, you must:
dynamic SQL
• Prepare the DynamicStagingArea in all formats except Format 1
• Describe the DynamicDescriptionArea in Format 4
• Execute the statements in the appropriate order
Preparing and describing the data types Since the SQLSA staging area is
the only connection between the execution of a SQL statement and a
transaction object, an execution error will occur if you do not prepare the SQL
statement correctly.
In addition to SQLSA and SQLDA, you can declare other variables of the
DynamicStagingArea and DynamicDescriptionArea data types. However, this
is required only when your script requires simultaneous access to two or more
dynamically prepared statements.
This is a valid dynamic cursor:
DECLARE my_cursor DYNAMIC CURSOR FOR SQLSA ;
PREPARE SQLSA FROM "SELECT emp_id FROM employee" ;
OPEN DYNAMIC my_cursor ;
This is an invalid dynamic cursor (there is no PREPARE, and therefore an
execution error will occur):
DECLARE my_cursor DYNAMIC CURSOR FOR SQLSA ;
OPEN DYNAMIC my_cursor ;
Statement order Where you place the dynamic SQL statements in your
scripts is unimportant, but the order of execution is important in Formats 2, 3,
and 4. You must execute:
1 The DECLARE and the PREPARE before you execute any other dynamic
SQL statements
2 The OPEN in Formats 3 and 4 before the FETCH
3 The CLOSE at the end
If you have multiple PREPARE statements, the order affects the contents of
SQLSA.
These statements illustrate the correct ordering:
DECLARE my_cursor DYNAMIC CURSOR FOR SQLSA
180
Chapter 8 SQL Statements
181
Dynamic SQL Format 1
Examples These statements create a database table named Employee. The statements use
the string Mysql to store the CREATE statement.
string Mysql
Mysql = "CREATE TABLE Employee "&
+"(emp_id integer not null,"&
+"dept_id integer not null, "&
+"emp_fname char(10) not null, "&
+"emp_lname char(20) not null)"
EXECUTE IMMEDIATE :Mysql ;
These statements assume a transaction object named My_trans exists and is
connected:
string Mysql
Mysql="INSERT INTO dept Values (1234, ’Purchasing’)"
EXECUTE IMMEDIATE :Mysql USING My_trans ;
182
Chapter 8 SQL Statements
183
Dynamic SQL Format 2
PREPARE SQLSA
FROM "INSERT INTO dept VALUES (?,?)" ;
EXECUTE SQLSA USING :Dept_id_var,:Dept_name_var ;
184
Chapter 8 SQL Statements
185
Dynamic SQL Format 3
If your DBMS supports formats of FETCH other than the customary (and
default) FETCH NEXT, you can specify FETCH FIRST, FETCH PRIOR, or
FETCH LAST.
The FETCH and CLOSE statements in Format 3 are the same as in standard
embedded SQL.
To declare a local cursor or procedure, open the script in the Script view and
select Paste SQL from the PainterBar or the Edit>Paste Special menu. To
declare a global, instance, or shared cursor or procedure, select Declare from
the first dropdown listbox in the Script view and Global Variables, Instance
Variables, or Shared Variables from the second dropdown listbox, then select
Paste SQL.
For information about global, instance, shared, and local scope, see "Where to
declare variables" on page 36.
Examples Example 1 These statements associate a cursor named my_cursor with
SQLSA, prepare a SELECT statement in SQLSA, open the cursor, and return
the employee ID in the current row into the PowerScript variable Emp_id_var:
integer Emp_id_var
DECLARE my_cursor DYNAMIC CURSOR FOR SQLSA ;
PREPARE SQLSA FROM "SELECT emp_id FROM employee" ;
OPEN DYNAMIC my_cursor ;
FETCH my_cursor INTO :Emp_id_var ;
CLOSE my_cursor ;
You can loop through the cursor as you can in embedded static SQL.
Example 2 These statements associate a cursor named my_cursor with
SQLSA, prepare a SELECT statement with one parameter in SQLSA, open the
cursor, and substitute the value of the variable Emp_state_var for the parameter
in the SELECT statement. The employee ID in the active row is returned into
the PowerBuilder variable Emp_id_var:
DECLARE my_cursor DYNAMIC CURSOR FOR SQLSA ;
integer Emp_id_var
string Emp_state_var = "MA"
string sqlstatement
186
Chapter 8 SQL Statements
187
Dynamic SQL Format 4
188
Chapter 8 SQL Statements
Parameter Description
DynamicDescriptionArea The name of the DynamicDescriptionArea (usually
SQLDA)
If you need a DynamicDescriptionArea variable
other than SQLDA, you must declare it and
instantiate it with the CREATE statement before
using it
Usage The DECLARE statement is not executable and can be defined globally.
If your DBMS supports formats of FETCH other than the customary (and
default) FETCH NEXT, you can specify FETCH FIRST, FETCH PRIOR, or
FETCH LAST.
To declare a local cursor or procedure, open the script in the Script view and
select Paste SQL from the PainterBar or the Edit>Paste Special menu. To
declare a global, instance, or shared cursor or procedure, select Declare from
the first dropdown listbox in the Script view and Global Variables, Instance
Variables, or Shared Variables from the second dropdown listbox, then select
Paste SQL.
For information about global, instance, shared, and local scope, see "Where to
declare variables" on page 36.
Accessing attribute information When a statement is described into a
DynamicDescriptionArea, this information is available to you in the attributes
of that DynamicDescriptionArea variable:
Information Attribute
Number of input parameters NumInputs
Array of input parameter types InParmType
Number of output parameters NumOutputs
Array of output parameter types OutParmType
189
Dynamic SQL Format 4
190
Chapter 8 SQL Statements
Examples Example 1 These statements assume you know that there will be only one
output descriptor and that it will be an integer. You can expand this example to
support any number of output descriptors and any data type by wrapping the
CHOOSE CASE statement in a loop and expanding the CASE statements:
string Stringvar, Sqlstatement
integer Intvar
Sqlstatement = "SELECT emp_id FROM employee"
PREPARE SQLSA FROM :Sqlstatement ;
DESCRIBE SQLSA INTO SQLDA ;
DECLARE my_cursor DYNAMIC CURSOR FOR SQLSA ;
OPEN DYNAMIC my_cursor USING DESCRIPTOR SQLDA ;
FETCH my_cursor USING DESCRIPTOR SQLDA ;
// If the FETCH is successful, the output
// descriptor array will contain returned
// values from the first row of the result set.
// SQLDA.NumOutputs contains the number of
// output descriptors.
// The SQLDA.OutParmType array will contain
// NumOutput entries and each entry will contain
// an value of the enumerated data type ParmType
// (such as TypeInteger!, or TypeString!).
CHOOSE CASE SQLDA.OutParmType[1]
CASE TypeString!
Stringvar = GetDynamicString(SQLDA, 1)
CASE TypeInteger!
Intvar = GetDynamicNumber(SQLDA, 1)
END CHOOSE
CLOSE my_cursor ;
Example 2 These statements assume you know there is one string input
descriptor and sets the parameter to MA:
string Sqlstatement
Sqlstatement = "SELECT emp_id FROM employee "&
+"WHERE emp_state = ?"
PREPARE SQLSA FROM :Sqlstatement ;
191
Dynamic SQL Format 4
CLOSE my_cursor ;
192
CH A PTE R 9 PowerScript Events
About this chapter This chapter discusses events in general and then documents the
arguments, event IDs, and return codes for the events defined for all
PowerBuilder controls and objects except the DataWindow and
DataStore. Usage notes and examples provide information about what is
typically done in an event’s script.
For information about DataWindow and DataStore events, see the
DataWindow Reference.
Contents The events are listed in alphabetical order.
193
About events
About events
In PowerBuilder, there are several types of events:
Type Occurs in response to
System events with an ID User actions or other system messages or a call in
your scripts
System events without an ID PowerBuilder messages or a call in your scripts
User-defined events with an ID User actions or other system messages or a call in
your scripts
User-defined events without an A call in your scripts
ID
The following information about event IDs, arguments, and return values
applies to all types of events.
Event IDs An event ID connects an event to a system message. Events that can be
triggered by user actions or other system activity have event IDs. In
PowerBuilder’s objects, PowerBuilder defines events for commonly used
event IDs. These events are documented in this chapter. You can define your
own events for other system messages using the event IDs listed in the Event
Declaration dialog box.
Events without IDs Some system events, such as the application object’s
Open event, do not have an event ID. They are associated with PowerBuilder
activity, not system activity. PowerBuilder triggers them itself when
appropriate.
Arguments System-triggered events Each system event has its own list of zero or more
arguments. When PowerBuilder triggers the event in response to a system
message, it supplies values for the arguments, which become available in the
event script.
Events you trigger If you trigger a system event in another event script, you
specify the expected arguments. For example, in the Clicked event for a
window, you could trigger the DoubleClicked event with this statement,
passing its flags, xpos, and ypos arguments on to the DoubleClicked event.
w_main.EVENT DoubleClicked(flags, xpos, ypos)
Because DoubleClicked is a system event, the argument list is fixed—you can’t
supply additional arguments of your own.
194
Chapter 9 PowerScript Events
Return values Where does the return value go? Most events have a return value. When
the event is triggered by the system, the return value is returned to the system.
When your script triggers a user-defined or system event, you can capture the
return value in an assignment statement:
li_rtn = w_main.EVENT process_info(mydata)
When you post an event, the return value is lost because the calling script is no
longer running when the posted script is actually run. The compiler does not
allow a posted event in an assignment statement.
Return codes System events with return values have a default return code of
0, which means take no special action and continue processing. Some events
have additional codes that you can return to change the processing that happens
after the event. For example, a return code might allow you to suppress an error
message or prevent a change from taking place.
A RETURN statement is not required in an event script, but for most events it
is good practice to include one. For events with return values, if you don’t have
a RETURN statement, the event returns 0.
Some system events have no return value. For these events, the compiler does
not allow a RETURN statement.
Ancestor event script Sometimes you want to perform some processing in an event in a descendent
return values object, but that processing depends on the return value of the ancestor event
script. You can use a local variable called AncestorReturnValue that is
automatically declared and assigned the value of the ancestor event.
For more information about AncestorReturnValue, see "Calling functions and
events in an object’s ancestor" on page 117.
User-defined events With an ID When you declare a user-defined event that will be triggered by a
system message, you select an event ID from the list of IDs. The pbm codes
listed in the Event dialog box map to system messages.
The return value and arguments associated with the event ID become part of
your event declaration. You cannot modify them.
When the corresponding system message occurs, PowerBuilder triggers the
event and passes values for the arguments to the event script.
195
About events
Without an ID When you declare a user event that will not be associated with
a system message, you do not select an event ID for the event.
You can specify your own arguments and return data type in the Event
Declaration dialog box.
The event will never be triggered by user actions or system activity. You will
trigger the event yourself in your application’s scripts.
For more information If you want to trigger events, including system events, see "Syntax for calling
PowerBuilder functions and events" on page 113 for information on the calling
syntax.
To learn more about user-defined events, see the PowerBuilder User’s Guide.
196
Chapter 9 PowerScript Events
Activate
Description Occurs just before the window becomes active.
Event ID
Event ID Objects
pbm_activate Window
Arguments None
Return codes Long. Return code choices (specify in a RETURN statement):
0 Continue processing
Usage When an Activate event occurs, the first object in the tab order for the window
gets focus. If there are no visible objects in the window, the window gets focus.
An Activate event occurs for a newly opened window because it is made active
after it is opened.
The Activate event is frequently used to enable and disable menu items.
Examples Example 1 In the window’s Activate event, this code disables the Sheet
menu item for menu m_frame on the File menu:
m_frame.m_file.m_sheet.Enabled = FALSE
Example 2 This code opens the sheet w_sheet in a layered style when the
window activates:
w_sheet.ArrangeSheets(Layer!)
See also Close
Open
Show
197
BeginDrag
BeginDrag
The BeginDrag event has different arguments for different objects:
Object See
ListView control Syntax 1
TreeView control Syntax 2
Arguments
Argument Description
index Integer by value (the index of the ListView item being
dragged)
198
Chapter 9 PowerScript Events
Examples This example moves a ListView item from one ListView to another.
Ilvi_dragged_object is a window instance variable whose type is
ListViewItem. To copy the item, omit the code that deletes it from the source
ListView.
This code is in the BeginDrag event script of the source ListView.
// If the TreeView’s DragAuto property is FALSE
This.Drag(Begin!)
This.GetItem(This.SelectedIndex(), &
ilvi_dragged_object)
Arguments
Argument Description
handle Long by value (handle of the TreeView item being
dragged)
199
BeginDrag
Usage BeginDrag and BeginRightDrag events occur when the user presses the mouse
button and drags, whether or not dragging is enabled. To enable dragging, you
can:
• Set the DragAuto property to TRUE. If the TreeView’s DragAuto property
is TRUE, a drag operation begins automatically when the user clicks.
• Call the Drag function. If DragAuto is FALSE, then in the BeginDrag
event script, the programmer can call the Drag function to begin the drag
operation.
The user cannot drag a highlighted item.
Dragging a TreeView item onto another control causes the control’s standard
drag events (DragDrop, DragEnter, DragLeave, and DragWithin) to occur. The
standard drag events occur for TreeView when another control is dragged
within the borders of the TreeView.
Examples This example moves the first TreeView item in the source TreeView to another
TreeView when the user drags there. Itvi_dragged_object is a window instance
variable whose type is TreeViewItem. To copy the item, omit the code that
deletes it from the source TreeView.
This code is in the BeginDrag event script of the source TreeView:
long itemnum
200
Chapter 9 PowerScript Events
BeginLabelEdit
The BeginLabelEdit event has different arguments for different objects:
Object See
ListView control Syntax 1
TreeView control Syntax 2
Arguments
Argument Description
index Integer by value (the index of the selected ListView item)
201
BeginLabelEdit
Event ID
Event ID Objects
pbm_tvnbeginlabeledit TreeView
Arguments
Argument Description
handle Long by value (the handle of the selected TreeView item)
202
Chapter 9 PowerScript Events
BeginRightDrag
The BeginRightDrag event has different arguments for different objects:
Object See
ListView control Syntax 1
TreeView control Syntax 2
Arguments
Argument Description
index Integer by value (the index of the ListView item being
dragged)
203
BeginRightDrag
DragDrop
DragEnter
DragLeave
DragWithin
Arguments
Argument Description
handle Long by value (the handle of the TreeView item being
dragged)
204
Chapter 9 PowerScript Events
DragEnter
DragLeave
DragWithin
205
Clicked
Clicked
The Clicked event has different arguments for different objects:
Object See
Menus Syntax 1
ListView control Syntax 2
Tab control Syntax 3
TreeView control Syntax 4
Window Syntax 5
Other controls Syntax 6
For information about the DataWindow control’s Clicked event, see the
DataWindow Reference.
Arguments None
Return codes None (do not use a RETURN statement)
Usage If the user highlights the menu item without choosing it, its Selected event
occurs.
If the user chooses a menu item that has a cascaded menu associated with it,
the Clicked event occurs and the cascaded menu is displayed.
Examples This script is for the Clicked event of the New menu item for the frame
window. The wf_newsheet function is a window function. The window
w_genapp_frame is part of the application template you can generate when you
create a new application:
/* Create a new sheet */
w_genapp_frame.wf_newsheet( )
See also Selected
206
Chapter 9 PowerScript Events
Arguments
Argument Description
index Integer by value (the index of the ListView item the user
clicked)
The value of index is -1 if the user clicks within the control
but not on a specific item
Examples This code changes the label of the item the user clicks to uppercase:
IF index = -1 THEN RETURN 0
This.GetItem(index, llvi_current)
llvi_current.Label = Upper(llvi_current.Label)
This.SetItem(index, llvi_current)
RETURN 0
See also ColumnClick
DoubleClicked
ItemActivate
ItemChanged
ItemChanging
207
Clicked
RightClicked
RightDoubleClicked
Arguments
Argument Description
index Integer by value (the index of the tab page the user clicked)
208
Chapter 9 PowerScript Events
Arguments
Argument Description
handle Long by value (the handle of the TreeView item the user
clicked)
This.GetItem(handle, ltvi_current)
ltvi_current.Label = Upper(ltvi_current.Label)
This.SetItem(handle, ltvi_current)
See also DoubleClicked
RightClicked
RightDoubleClicked
SelectionChanged
SelectionChanging
209
Clicked
Event ID
Event ID Objects
pbm_lbuttonclk Window
Arguments
Argument Description
flags UnsignedLong by value (the modifier keys and mouse
buttons that are pressed)
Values are:
• 1 — Left mouse button
• 2 — Right mouse button
• 4 — SHIFT key
• 8 — CTRL key
• 16 — Middle mouse button
In the Clicked event, the left mouse button is being
released, so 1 is not summed in the value of flags
For an explanation of flags, see Syntax 2 of MouseMove
on page 279
xpos Integer by value (the distance of the pointer from the left
edge of the window’s workspace in pixels)
ypos Integer by value (the distance of the pointer from the top of
the window’s workspace in pixels)
210
Chapter 9 PowerScript Events
Arguments None
Return codes Long. Return code choices (specify in a RETURN statement):
0 Continue processing
Usage The Clicked event occurs when the user releases the mouse button.
If another control had focus, then a GetFocus and a Clicked event occur for the
control the user clicks.
Examples This code in an OLE control’s Clicked event activates the object in the control:
integer li_success
li_success = This.Activate(InPlace!)
See also GetFocus
RButtonDown
211
Close
Close
The Close event has different arguments for different objects:
Object See
Application Syntax 1
OLE control Syntax 2
Window Syntax 3
Arguments None
Return codes None (do not use a RETURN statement)
Usage The Close event occurs when the last window (for MDI applications the MDI
frame) is closed.
See also Open
SystemError
Arguments None
Return codes Long. Return code: Ignored
Usage If the user closed the OLE server, the user’s choices may cause the OLE object
in the control to be updated, triggering the Save or DataChange events.
212
Chapter 9 PowerScript Events
If you want to retrieve the ObjectData blob value of an OLE control during the
processing of this event, you must post a user event back to the control or you
will generate a runtime error.
See also DataChange
Save
Arguments None
Return codes Long. Return code choices (specify in a RETURN statement):
0 Continue processing
Usage When you call the Close function for the window, a CloseQuery event occurs
before the Close event. In the CloseQuery event, you can specify a return code
to prevent the Close event from occurring and the window from closing.
Do not trigger the Close event to close a window; call the Close function
instead. (Triggering the event simply runs the script and does not close the
window.)
See also CloseQuery
Open
213
CloseQuery
CloseQuery
Description Occurs when a window is closed, before the Close event.
Event ID
Event ID Objects
pbm_closequery Window
Arguments None
Return codes Long. Return code choices (specify in a RETURN statement):
0 Allow the window to be closed
1 Prevent the window from closing
Usage If the CloseQuery event returns a value of 1, the closing of the window is
aborted and the Close event that usually follows CloseQuery does not occur.
If the user closes the window with the Close box (instead of using buttons
whose scripts can evaluate the state of the data in the window), the CloseQuery
event still occurs, allowing you to prompt the user about saving changes or to
check whether data the user entered is valid.
Obsolete techniques
You no longer need to set the ReturnValue property of the Message object. Use
a RETURN statement instead.
Examples This statement in the CloseQuery event for a window asks if the user really
wants to close the window and if the user answers no, prevents it from closing:
IF MessageBox("Closing window", "Are you sure?", &
Question!, YesNo!) = 2 THEN
RETURN 1
ELSE
RETURN 0
END IF
This script for the CloseQuery event tests to see if the DataWindow dw_1 has
any pending changes. If it has, it asks the user whether to update the data and
close the window, close the window without updating, or leave the window
open without updating:
integer li_rc
214
Chapter 9 PowerScript Events
//User canceled
ELSE
RETURN 1
END IF
ELSE
// No changes to the data, window will just close
RETURN 0
END IF
215
ColumnClick
ColumnClick
Description Occurs when the user clicks a column header.
Event ID
Event ID Objects
pbm_lvncolumnclick ListView
Arguments
Argument Description
column The index of the clicked column
ii_col = column
This.GetColumn(column, ls_label, la_align, &
li_width)
CASE Left!
rb_left.Checked = TRUE
ls_align = "Left!"
CASE Center!
rb_center.Checked = TRUE
ls_align = "Center!"
CASE Justify!
rb_just.Checked = TRUE
ls_align = "Justify!"
END CHOOSE
216
Chapter 9 PowerScript Events
217
ConnectionBegin
ConnectionBegin
Description Obsolete event. Used for distributed PowerBuilder connections.
218
Chapter 9 PowerScript Events
ConnectionEnd
Description Obsolete event. Used for distributed PowerBuilder connections.
219
Constructor
Constructor
Description Occurs when the control or object is created, just before the Open event for the
window that contains the control.
Event ID
Event ID Objects
pbm_constructor All objects
Arguments None
Return codes Long. Return code choices (specify in a RETURN statement):
0 Continue processing
Usage You can write a script for a control’s Constructor event to affect the control’s
properties before the window is displayed.
When a window or user object opens, a Constructor event for each control in
the window or user object occurs. The order of controls in a window’s Control
property (which is an array) determines the order in which Constructor events
are triggered. If one of the controls in the window is a user object, the
Constructor events of all the controls in the user object occur before the
Constructor event for the next control in the window.
When you call OpenUserObject to add a user object to a window dynamically,
its Constructor event and the Constructor events for all of its controls occur.
When you use the CREATE statement to instantiate a class (nonvisual) user
object, its Constructor event occurs.
When a class user object variable has an Autoinstantiate setting of TRUE, its
Constructor event occurs when the variable comes into scope. Therefore, the
Constructor event occurs for:
• Global variables when the system starts up
• Shared variables when the object with the shared variables is loaded
• Instance variables when the object with the instance variables is created
• Local variables when the function that declares them begins executing
Examples This example retrieves data for the DataWindow dw_1 before its window is
displayed:
dw_1.SetTransObject(SQLCA)
dw_1.Retrieve( )
See also Destructor
Open
220
Chapter 9 PowerScript Events
DataChange
Description Occurs when the server application notifies the control that data has changed.
Event ID
Event ID Objects
pbm_omndatachange OLE
Arguments None
Return codes Long. Return code: Ignored
See also PropertyRequestEdit
PropertyChanged
Rename
ViewChange
221
Deactivate
Deactivate
Description Occurs when the window becomes inactive.
Event ID
Event ID Objects
pbm_deactivate Window
Arguments None
Return codes Long. Return code choices (specify in a RETURN statement):
0 Continue processing
Usage When a window is closed, a Deactivate event occurs.
See also Activate
Show
222
Chapter 9 PowerScript Events
DeleteAllItems
Description Occurs when all the items in the ListView are deleted.
Event ID
Event ID Objects
pbm_lvndeleteallitems ListView
Arguments None
Return codes Long. Return code choices (specify in a RETURN statement):
0 Continue processing
Examples This example uses the DeleteAllItems event to ensure that there’s a default
item in the ListView control:
This.AddItem("Default item", 1)
See also DeleteItem
InsertItem
223
DeleteItem
DeleteItem
The DeleteItem event has different arguments for different objects:
Object See
ListView control Syntax 1
TreeView control Syntax 2
Arguments
Argument Description
index Integer by value (the index of the deleted item)
224
Chapter 9 PowerScript Events
Arguments
Argument Description
handle Long by value (the handle of the deleted item)
This.GetItem(handle, ll_tvi)
MessageBox("Message", String(ll_tvi.Label) &
+ " has been deleted.")
225
Destructor
Destructor
Description Occurs when the user object or control is destroyed, immediately after the
Close event of a window.
Event ID
Event ID Objects
pbm_destructor All objects
Arguments None
Return codes Long. Return code choices (specify in a RETURN statement):
0 Continue processing
Usage When a window is closed, each control’s Destructor event destroys the control
and removes it from memory. After they’ve been destroyed, you can no longer
refer to those controls in other scripts (if you do, a runtime error occurs).
See also Constructor
Close
226
Chapter 9 PowerScript Events
DoubleClicked
The DoubleClicked event has different arguments for different objects:
Object See
ListBox, PictureListBox, ListView, and Tab controls Syntax 1
TreeView control Syntax 2
Window Syntax 3
Other controls Syntax 4
For information about the DataWindow control’s DoubleClicked event, see the
DataWindow Reference.
Arguments
Argument Description
index Integer by value
The index of the item the user double-clicked (for tabs, the
index of the tab page)
227
DoubleClicked
Arguments
Argument Description
handle Long by value (the handle of the item the user double-
clicked)
228
Chapter 9 PowerScript Events
Arguments
Argument Description
flags UnsignedLong by value (the modifier keys and mouse
buttons that are pressed)
Values are:
• 1 — Left mouse button
• 2 — Right mouse button
• 4 — SHIFT key
• 8 — CTRL key
• 16 — Middle mouse button
In the Clicked event, the left mouse button is being
released, so 1 is not summed in the value of flags
For an explanation of flags, see Syntax 2 of MouseMove
on page 279
xpos Integer by value (the distance of the pointer from the left
edge of the window’s workspace in pixels)
ypos Integer by value (the distance of the pointer from the top
of the window’s workspace in pixels)
229
DoubleClicked
230
Chapter 9 PowerScript Events
Arguments None
Return codes Long. Return code choices (specify in a RETURN statement):
0 Continue processing
Usage The DoubleClicked event for DropDownListBoxes is only active when the
Always Show List property is on.
See also Clicked
RButtonDown
231
DragDrop
DragDrop
The DragDrop event has different arguments for different objects:
Object See
ListBox, PictureListBox, ListView, and Syntax 1
Tab controls
TreeView control Syntax 2
Windows and other controls Syntax 3
For information about the DataWindow control’s DragDrop event, see the
DataWindow Reference.
Arguments
Argument Description
source DragObject by value (a reference to the control being
dragged)
index Integer by value (the index of the target ListView item)
232
Chapter 9 PowerScript Events
Arguments
Argument Description
source DragObject by value (a reference to the control being
dragged)
handle Long by value (the handle of the target TreeView item)
233
DragDrop
Arguments
Argument Description
source DragObject by value (a reference to the control being
dragged)
234
Chapter 9 PowerScript Events
long ll_currow
dwitemstatus ldwis_delrow
ll_currow = dw_orddetail.GetRow( )
ldw_Source = source
ll_RowToDelete = ldw_Source.GetRow()
ELSE
Beep(1)
END IF
See also DragEnter
DragLeave
DragWithin
235
DragEnter
DragEnter
Description Occurs when the user is dragging an object and enters the control.
Event ID
Event ID Objects
pbm_bndragenter CheckBox, CommandButton, Graph, Picture,
PictureHyperlink, PictureButton, RadioButton
pbm_cbndragenter DropDownListBox, DropDownPictureListBox
pbm_dwndragenter DataWindow
pbm_endragenter SingleLineEdit, EditMask, MultiLineEdit, StaticText,
StaticHyperLink
pbm_lbndragenter ListBox, PictureListBox
pbm_lvndragenter ListView
pbm_omndragenter OLE
pbm_prndragenter HProgressBar, VProgressBar
pbm_rendragenter RichTextEdit
pbm_sbndragenter HScrollBar, HTrackBar, VScrollBar, VTrackBar
pbm_tcndragenter Tab
pbm_tvndragenter TreeView
pbm_uondragenter UserObject
pbm_dragenter Window
Arguments
Argument Description
source DragObject by value (a reference to the control being
dragged)
236
Chapter 9 PowerScript Events
DragLeave
Description Occurs when the user is dragging an object and leaves the control.
Event ID
Event ID Objects
pbm_bndragleave CheckBox, CommandButton, Graph, Picture,
PictureHyperLink, PictureButton, RadioButton
pbm_cbndragleave DropDownListBox, DropDownPictureListBox
pbm_dwndragleave DataWindow
pbm_endragleave SingleLineEdit, EditMask, MultiLineEdit, StaticText,
StaticHyperLink
pbm_lbndragleave ListBox, PictureListBox
pbm_lvndragleave ListView
pbm_omndragleave OLE
pbm_prndragleave HProgressBar, VProgressBar
pbm_rendragleave RichTextEdit
pbm_sbndragleave HScrollBar, HTrackBar, VScrollBar, VTrackBar
pbm_tcndragleave Tab
pbm_tvndragleave TreeView
pbm_uondragleave UserObject
pbm_dragleave Window
Arguments
Argument Description
source DragObject by value (a reference to the control being
dragged)
237
DragLeave
238
Chapter 9 PowerScript Events
DragWithin
The DragWithin event has different arguments for different objects:
Object See
ListBox, PictureListBox, ListView, and Syntax 1
Tab controls
TreeView control Syntax 2
Windows and other controls Syntax 3
For information about the DataWindow control’s DragWithin event, see the
DataWindow Reference.
Arguments
Argument Description
source DragObject by value (a reference to the control being
dragged)
index Integer by value (a reference to the ListView item under
the pointer in the ListView control)
239
DragWithin
Arguments
Argument Description
source DragObject by value (a reference to the control being
dragged)
handle Long (a reference to the ListView item under the pointer
in the TreeView control)
240
Chapter 9 PowerScript Events
Event ID Objects
pbm_sbndragwithin HScrollBar, HTrackBar, VScrollBar, VTrackBar
pbm_uondragwithin UserObject
pbm_dragwithin Window
Arguments
Argument Description
source DragObject by value (a reference to the control being
dragged)
241
EndLabelEdit
EndLabelEdit
The EndLabelEdit event has different arguments for different objects:
Object See
ListView control Syntax 1
TreeView control Syntax 2
Arguments
Argument Description
index Integer. The index of the ListView item for which you
have edited the label
newlabel The string that represents the new label for the ListView
item
242
Chapter 9 PowerScript Events
Event ID
Event ID Objects
pbm_tvnendlabeledit TreeView
Arguments
Argument Description
handle Integer. The index of the TreeView item for which you
have edited the label
newtext The string that represents the new label for the TreeView
item
This.GetItem(handle, tvi)
sle_info.Text = "Finished editing " &
+ String(tvi.Label) &
+ ". Item changed to " &
+ String(newtext)
See also BeginLabelEdit
243
Error
Error
Description Occurs when an error is found in a data or property expression for an external
object or a DataWindow object. Also occurs when a communications error is
found in a client connecting to EAServer.
Event ID
Event ID Objects
None Connection, DataWindow, DataStore, JaguarORB, OLE,
OLEObject, OLETxnObject
Arguments
Argument Description
errornumber Unsigned integer by value (PowerBuilder’s error number)
errortext String, read-only (PowerBuilder’s error message)
errorwindowmenu String, read-only (the name of the window or menu that is
the parent of the object whose script caused the error)
errorobject String, read-only (the name of the object whose script
caused the error)
errorscript String, read-only (the full text of the script in which the
error occurred)
errorline Unsigned integer by value (the line in the script where the
error occurred)
244
Chapter 9 PowerScript Events
Argument Description
action ExceptionAction by reference
A value you specify to control the application’s course of
action as a result of the error. Values are:
• ExceptionFail! — Fail as if this script were not
implemented. The error condition triggers any active
event handlers, or if none, the SystemError event
• ExceptionIgnore! — Ignore this error and return as if
no error occurred (use this option with caution because
the conditions that caused the error can cause another
error)
• ExceptionRetry! — Execute the function or evaluate
the expression again in case the OLE server was not
ready. This option is not valid for DataWindows
• ExceptionSubstituteReturnValue! — Use the value
specified in the returnvalue argument instead of the
value returned by the OLE server or DataWindow and
cancel the error condition
returnvalue Any by reference (a value whose data type matches the
expected value that the OLE server or DataWindow would
have returned)
This value is used when the value of action is
ExceptionSubstituteReturnValue!
245
Error
246
Chapter 9 PowerScript Events
ExternalException
Description Occurs when an OLE automation command caused an exception on the OLE
server.
Event ID
Event ID Objects
None OLE, OLEObject, OLETxnObject
Arguments
Argument Description
resultcode UnsignedLong by value (a PowerBuilder number
identifying the exception that occurred on the server)
exceptioncode UnsignedLong by value (a number identifying the error
that occurred on the server. For the meaning of the code,
see the server documentation)
source String by value (the name of the server (provided by the
server))
description String by value (a description of the exception (provided
by the server))
helpfile String by value (the name of a Help file containing
information about the exception (provided by the server))
helpcontext UnsignedLong by value (the context ID of a Help topic in
helpfile containing information about the exception
(provided by the server))
247
ExternalException
Argument Description
action ExceptionAction by reference
A value you specify to control the application’s course of
action as a result of the error. Values are:
• ExceptionFail! — Fail as if this script were not
implemented. The error condition triggers the
SystemError event
• ExceptionIgnore! — Ignore this error and return as if no
error occurred (use this option with caution because the
conditions that caused the error can cause another error)
• ExceptionRetry! — Execute the function or evaluate
the expression again in case the OLE server was not
ready
• ExceptionSubstituteReturnValue! — Use the value
specified in the returnvalue argument instead of the
value returned by the OLE server or DataWindow and
cancel the error condition
returnvalue Any by reference
A value whose data type matches the expected value that
the OLE server would have returned. This value is used
when the value of action is
ExceptionSubstituteReturnValue!
248
Chapter 9 PowerScript Events
action = ie_action
returnvalue = ia_substitute
Because the event script must serve for every automation command for the
control, you would need to set the instance variables to appropriate values
before each automation command.
See also Error
249
FileExists
FileExists
Description Occurs when a file is saved in the RichTextEdit control and the file already
exists.
Event ID
Event ID Objects
pbm_renfileexists RichTextEdit
Arguments
Argument Description
filename The name of the file
250
Chapter 9 PowerScript Events
GetFocus
Description Occurs just before the control receives focus (before it is selected and becomes
active).
Applies to all controls
Event ID
Event ID Objects
pbm_bnsetfocus CheckBox, CommandButton, Graph, OLE, Picture,
PictureHyperLink, PictureButton, RadioButton
pbm_cbnsetfocus DropDownListBox, DropDownPictureListBox
pbm_dwnsetfocus DataWindow
pbm_ensetfocus SingleLineEdit, EditMask, MultiLineEdit, StaticText,
StaticHyperLink
pbm_lbnsetfocus ListBox, PictureListBox
pbm_lvnsetfocus ListView
pbm_prnsetfocus HProgressBar, VProgressBar
pbm_rensetfocus RichTextEdit
pbm_sbnsetfocus HScrollBar, HTrackBar, VScrollBar, VTrackBar
pbm_tcnsetfocus Tab
pbm_tvnsetfocus TreeView
Arguments None
Return codes Long. Return code choices (specify in a RETURN statement):
0 Continue processing
Examples Example 1 This example in a SingleLineEdit control’s GetFocus event
selects the text in the control when the user tabs to it:
This.SelectText(1, Len(This.Text))
Example 2 In Example 1, when the user clicks the SingleLineEdit rather than
tabbing to it, the control gets focus and the text is highlighted but then the click
deselects the text. If you define a user event that selects the text and then post
that event in the GetFocus event, the highlighting works when the user both
tabs and clicks. This code is in the GetFocus event:
This. EVENT POST ue_select( )
This code is in the ue_select user event:
This.SelectText(1, Len(This.Text))
See also Clicked
LoseFocus
251
Help
Help
Description Occurs when the user drags the question-mark button from the title bar to a
menu item or a control and then clicks, or when the user clicks in a control
(giving it focus) and then presses the F1 key.
Event ID
Event ID Objects
pbm_help Window, Menu, DragObject
Arguments
Argument Description
xpos Integer by value (the distance of the Help message from the
left edge of the screen, in PowerBuilder units)
ypos Integer by value (the distance of the Help message from the
top of the screen, in PowerBuilder units)
252
Chapter 9 PowerScript Events
Hide
Description Occurs just before the window is hidden.
Event ID
Event ID Objects
pbm_hidewindow Window
Arguments None
Return codes Long. Return code choices (specify in a RETURN statement):
0 Continue processing
Usage A Hide event can occur when a sheet in an MDI frame is closed. It does not
occur when closing a main, response, or popup window.
See also Close
Show
253
HotLinkAlarm
HotLinkAlarm
Description Occurs after a Dynamic Data Exchange (DDE) server application has sent new
(changed) data and the client DDE application has received it.
Event ID
Event ID Objects
pbm_ddedata Window
Arguments None
Return codes Long. Return code choices (specify in a RETURN statement):
0 Continue processing
Usage After establishing a hot link with a DDE server application with the
StartHotLink function, actions on the server can trigger the HotLinkAlarm
event.
Examples This script in the HotLinkAlarm event gets information about the DDE server
application and the new data:
string ls_data, ls_appl, ls_topic, ls_item
GetDataDDEOrigin(ls_appl, ls_topic, ls_item)
GetDataDDE(ls_data)
254
Chapter 9 PowerScript Events
Idle
Description Occurs when the Idle function has been called in an application object script
and the specified number of seconds have elapsed with no mouse or keyboard
activity.
Event ID
Event ID Objects
None Application
Arguments None
Return codes None (do not use a RETURN statement)
Examples This statement in an application script causes the Idle event to be triggered after
300 seconds of inactivity:
Idle(300)
In the Idle event itself, this statement closes the application:
HALT CLOSE
255
InputFieldSelected
InputFieldSelected
Description In a RichTextEdit control, occurs when the user has double-clicked or pressed
ENTER in an input field, allowing the user to edit the data in the field.
Event ID
Event ID Objects
pbm_reninputfieldselected RichTextEdit
Arguments
Argument Description
fieldname String by value (the name of the input field that was
selected)
256
Chapter 9 PowerScript Events
InsertItem
Description Occurs when an item is inserted in the ListView.
Event ID
Event ID Objects
pbm_lvninsertitem ListView
Arguments
Argument Description
index An integer that represents the index of the item being
inserted into the ListView
257
ItemActivate
ItemActivate
Description Occurs when a ListView item is clicked or double-clicked. The actual firing
mechanism depends on the OneClickActivate and TwoClickActivate property
settings.
Event ID
Event ID Objects
pbm_lvnitemactivate ListView
Arguments
Argument Description
Index An integer that represents the index of the item being
inserted into the ListView
Examples This code changes a ListView item text label to uppercase lettering. The
change is made in the second column of the item the user clicks or double-
clicks, depending on the ListView property settings:
listviewitem llvi_current
This.GetItem(index, 2, llvi_current)
llvi_current.Label = Upper(llvi_current.Label)
This.SetItem(index, 2, llvi_current)
RETURN 0
See also ItemChanged
ItemChanging
258
Chapter 9 PowerScript Events
ItemChanged
Description Occurs when an ListView item has changed.
Event ID
Event ID Objects
pbm_lvnitemchanged ListView
Arguments
Argument Description
index The index of the item that is changing
focuschanged Boolean (specifies if focus has changed for the item)
hasfocus Boolean (specifies whether the item has focus)
selectionchange Boolean (specifies whether the selection has changed for
the item)
selected Boolean (specifies whether the item is selected)
otherchange Boolean (specifies if anything other than focus or selection
has changed for the item)
259
ItemChanging
ItemChanging
Description Occurs just before a ListView changes.
Event ID
Event ID Objects
pbm_lvnitemchanging ListView
Arguments
Argument Description
index The index of the item that has changed
focuschange Boolean (specifies if focus is changing for the item)
hasfocus Boolean (specifies whether the item has focus)
selectionchange Boolean (specifies whether the selection is changing for
the item)
selected Boolean (specifies whether the item is selected)
otherchange Boolean (specifies if anything other than focus or selection
has changed for the item)
260
Chapter 9 PowerScript Events
ItemCollapsed
Description Occurs when a TreeView item has collapsed.
Event ID
Event ID Objects
pbm_tvnitemcollapsed TreeView
Arguments
Argument Description
handle Long by reference (the handle of the collapsed
TreeViewItem)
This.GetItem(handle, l_tvi)
261
ItemCollapsing
ItemCollapsing
Description Occurs when a TreeView item is collapsing.
Event ID
Event ID Objects
pbm_tvnitemcollapsing TreeView
Arguments
Argument Description
handle Long by reference (the handle of the collapsing item)
This.GetItem(handle, l_vti)
This.SetItem(handle, l_tvi)
See also ItemCollapsed
262
Chapter 9 PowerScript Events
ItemExpanded
Description Occurs when a TreeView item has expanded.
Event ID
Event ID Objects
pbm_tvnitemexpanded TreeView
Arguments
Argument Description
handle Long by reference (the handle of the expanded item)
This.GetItem(handle, l_tvi)
263
ItemExpanding
ItemExpanding
Description Occurs while a TreeView item is expanding.
Event ID
Event ID Objects
pbm_tvnitemexpanding TreeView
Arguments
Argument Description
handle Long by reference (the handle of the expanding
TreeView item)
This.GetItem(handle, l_tvi)
This.SetItem(handle, l_tvi)
See also ItemExpanded
264
Chapter 9 PowerScript Events
ItemPopulate
Description Occurs when a TreeView item is being populated with children.
Event ID
Event ID Objects
pbm_tvnitempopulate TreeView
Arguments
Argument Description
handle Long by reference (the handle of the TreeView item
being populated)
This.GetItem(handle, tvi)
sle_get.Text = "Populating TreeView item " &
+ String(tvi.Label) + " with children"
See also ItemExpanding
265
Key
Key
Description Occurs when the user presses a key.
Event ID
Event ID Objects
pbm_lvnkeydown ListView
pbm_renkey RichTextEdit
pbm_tcnkeydown Tab
pbm_tvnkeydown TreeView
pbm_keydown Window
Arguments
Argument Description
key KeyCode by value
A value of the KeyCode enumerated data type indicating
the key that was pressed (for example, KeyA! or KeyF1!)
keyflags UnsignedLong by value (the modifier keys that were
pressed with the key)
Values are:
1 SHIFT key
2 CTRL key
3 SHIFT and CTRL keys
266
Chapter 9 PowerScript Events
If the user presses a modifier key and holds it down while pressing another key,
the Key event occurs twice: once when the modifier key is pressed and again
when the second key is pressed. If the user releases the modifier key before
pressing the second key, the value of keyflags will change in the second
occurrence.
When the user releases a key, the Key event does not occur. Therefore, if the
user releases a modifier key, you don’t know the current state of the modifier
keys until another key is pressed.
Examples This example causes a beep when the user presses F1 or F2 as long as SHIFT and
CTRL are not pressed:
IF keyflags = 0 THEN
IF key = KeyF1! THEN
Beep(1)
ELSEIF key = KeyF2! THEN
Beep(20)
END IF
END IF
This line displays the value of keyflags when a key is pressed.
st_1.Text = String(keyflags)
See also SystemKey
267
LineDown
LineDown
Description Occurs when the user clicks the down arrow of the vertical scrollbar.
Event ID
Event ID Objects
pbm_sbnlinedown VScrollBar, VTrackBar
Arguments None
Return codes Long. Return code choices (specify in a RETURN statement):
0 Continue processing
Usage When the user clicks in a vertical scrollbar, nothing happens unless you have
scripts that change the scrollbar’s Position property. For the scrollbar arrows,
use the LineUp and LineDown events; for clicks in the scrollbar background
above and below the thumb, use the PageUp and PageDown event; for
dragging the thumb itself, use the Moved event.
Examples This code in the LineDown event causes the thumb to move down when the
user clicks on the down arrow of the vertical scrollbar and displays the
resulting position in the StaticText control st_1:
IF This.Position > This.MaxPosition - 1 THEN
This.Position = MaxPosition
ELSE
This.Position = This.Position + 1
END IF
268
Chapter 9 PowerScript Events
LineLeft
Description Occurs when the user clicks in the left arrow of the horizontal scrollbar.
Event ID
Event ID Objects
pbm_sbnlineup HScrollBar, HTrackBar
Arguments None
Return codes Long. Return code choices (specify in a RETURN statement):
0 Continue processing
Usage When the user clicks in a horizontal scrollbar, nothing happens unless you have
scripts that change the scrollbar’s Position property. For the scrollbar arrows,
use the LineLeft and LineRight events; for clicks in the scrollbar background
above and below the thumb, use the PageLeft and Right events; for dragging
the thumb itself, use the Moved event.
Examples This code in the LineLeft event causes the thumb to move left when the user
clicks on the left arrow of the horizontal scrollbar and displays the resulting
position in the StaticText control st_1:
IF This.Position < This.MinPosition + 1 THEN
This.Position = MinPosition
ELSE
This.Position = This.Position - 1
END IF
269
LineRight
LineRight
Description Occurs when right arrow of the horizontal scrollbar is clicked.
Event ID
Event ID Objects
pbm_sbnlinedown HScrollBar, HTrackBar
Arguments None
Return codes Long. Return code choices (specify in a RETURN statement):
0 Continue processing
Usage When the user clicks in a horizontal scrollbar, nothing happens unless you have
scripts that change the scrollbar’s Position property. For the scrollbar arrows,
use the LineLeft and LineRight events; for clicks in the scrollbar background
above and below the thumb, use the PageLeft and PageRight events; for
dragging the thumb itself, use the Moved event.
Examples This code in the LineRight event causes the thumb to move right when the user
clicks on the right arrow of the horizontal scrollbar and displays the resulting
position in the StaticText control st_1:
IF This.Position > This.MaxPosition - 1 THEN
This.Position = MaxPosition
ELSE
This.Position = This.Position + 1
END IF
270
Chapter 9 PowerScript Events
LineUp
Description Occurs when the up arrow of the vertical scrollbar is clicked.
Event ID
Event ID Objects
pbm_sbnlineup VScrollBar, VTrackBar
Arguments None
Return codes Long. Return code choices (specify in a RETURN statement):
0 Continue processing
Usage When the user clicks in a vertical scrollbar, nothing happens unless you have
scripts that change the scrollbar’s Position property. For the scrollbar arrows,
use the LineUp and LineDown events; for clicks in the scrollbar background
above and below the thumb, use the PageUp and PageDown events; for
dragging the thumb itself, use the Moved event.
Examples This code in the LineUp event causes the thumb to move up when the user
clicks on the up arrow of the vertical scrollbar and displays the resulting
position in the StaticText control st_1:
IF This.Position < This.MinPosition + 1 THEN
This.Position = MinPosition
ELSE
This.Position = This.Position - 1
END IF
271
LoseFocus
LoseFocus
Description Occurs just before a control receives focus (before it becomes selected and
active).
Event ID
Event ID Description
pbm_controltypekillfocus UserObject (standard visual user objects only)
pbm_bnkillfocus CheckBox, CommandButton, Graph, OLE, Picture,
PictureHyperLink, PictureButton, RadioButton,
StaticText, StaticHyperLink
pbm_cbnkillfocus DropDownListBox, DropDownPictureListBox
pbm_dwnkillfocus DataWindow
pbm_enkillfocus SingleLineEdit, EditMask, MultiLineEdit
pbm_lbnkillfocus ListBox, PictureListBox
pbm_lvnkillfocus ListView
pbm_prnkillfocus HProgressBar, VProgressBar
pbm_renkillfocus RichTextEdit
pbm_sbnkillfocus HScrollBar, HTrackBar, VScrollBar, VTrackBar
pbm_tcnkillfocus Tab
pbm_tvnkillfocus TreeView
Arguments None
Return codes Long. Return code choices (specify in a RETURN statement):
0 Continue processing
Usage Write a script for a control’s LoseFocus event if you want some processing to
occur when the user changes focus to another control.
For controls that contain editable text, losing focus can also cause a Modified
event to occur.
In a RichTextEdit control, a LoseFocus event occurs when the user clicks on
the control’s toolbar. The control does not actually lose focus.
Because the MessageBox function grabs focus, you should not use it when
focus is changing, such as in a LoseFocus event. Instead, you might display a
message in the window’s title or a MultiLineEdit.
Examples Example 1 In this script for the LoseFocus event of a SingleLineEdit
sle_town, the user is reminded to enter information if the textbox is left empty:
IF sle_town.Text = "" THEN
st_status.Text = "You have not specified a town."
END IF
272
Chapter 9 PowerScript Events
273
Modified
Modified
Description Occurs when the contents in the control has changed.
Event ID
Event ID Objects
pbm_cbnmodified DropDownListBox, DropDownPictureListBox
pbm_enmodified SingleLineEdit, EditMask, MultiLineEdit
pbm_renmodified RichTextEdit
Arguments None
Return codes Long. Return code choices (specify in a RETURN statement):
0 Continue processing
Usage For plain text controls, the Modified event occurs when the user indicates being
finished by pressing ENTER or tabbing away from the control.
For RichText Edit controls, the value of the Modified property controls the
Modified event. If the property is FALSE, the event occurs when the first
change occurs to the contents of the control. The change also causes the
property to be set to TRUE, which suppresses the Modified event. You can
restart checking for changes by setting the property back to FALSE.
Resetting the Modified property is useful when you insert a document in the
control, which triggers the event and sets the property (it is reporting the
change to the control’s contents). To find out when the user begins making
changes to the content, set the Modified property back to FALSE in the script
that opens the document. When the user begins editing, the property will be
reset to TRUE and the event will occur again.
A Modified event can be followed by a LoseFocus event.
Examples In this example, code in the Modified event performs validation on the text the
user entered in a SingleLineEdit control sle_color (if the user didn’t enter RED,
WHITE, or BLUE, a message box tells them what is valid input; for valid
input, the color of the text changes):
string ls_color
This.BackColor = RGB(150,150,150)
ls_color = Upper(This.Text)
CHOOSE CASE ls_color
CASE "RED"
This.TextColor = RGB(255,0,0)
CASE "BLUE"
274
Chapter 9 PowerScript Events
This.TextColor = RGB(0,0,255)
CASE "WHITE"
This.TextColor = RGB(255,255,255)
CASE ELSE
This.Text = ""
MessageBox("Invalid input", &
"Enter RED, WHITE, or BLUE.")
END CHOOSE
This is not a realistic example—user input of three specific choices is more
suited to a listbox; in a real situation, the allowed input might be more general.
See also LoseFocus
275
MouseDown
MouseDown
The MouseDown event has different arguments for different objects:
Object See
RichTextEdit control Syntax 1
Window Syntax 2
Arguments None
Return codes Long. Return code choices (specify in a RETURN statement):
0 Continue processing
Examples This code in a RichTextEdit control’s MouseDown event assigns text to the
SingleLineEdit sle_1 when the user presses the left mouse button:
sle_1.text = "Mouse Down"
See also Clicked
MouseMove
MouseUp
276
Chapter 9 PowerScript Events
Arguments
Argument Description
flags UnsignedLong by value (the modifier keys and mouse
buttons that are pressed)
Values are:
• 1 — Left mouse button
• 2 — Right mouse button
• 4 — SHIFT key
• 8 — CTRL key
• 16 — Middle mouse button
In the MouseDown event, the left mouse button is always
down, so 1 is always summed in the value of flags
For an explanation of flags, see Syntax 2 of MouseMove
on page 279
xpos Integer by value (the distance of the pointer from the left
edge of the window’s workspace in pixels)
ypos Integer by value (the distance of the pointer from the top of
the window’s workspace in pixels)
CASE 5
sle_mkey.Text = "SHIFT key pressed"
CASE 9
sle_mkey.Text = "CONTROL key pressed"
CASE 13
sle_mkey.Text = "SHIFT and CONTROL keys
277
MouseDown
pressed"
END CHOOSE
See also Clicked
MouseMove
MouseUp
278
Chapter 9 PowerScript Events
MouseMove
The MouseMove event has different arguments for different objects:
Object See
RichTextEdit control Syntax 1
Window Syntax 2
Arguments None
Return codes Long. Return code choices (specify in a RETURN statement):
0 Continue processing
See also Clicked
MouseDown
MouseUp
279
MouseMove
Arguments
Argument Description
flags UnsignedLong by value (the modifier keys and mouse
buttons that are pressed)
Values are:
• 1 — Left mouse button
• 2 — Right mouse button
• 4 — SHIFT key
• 8 — CTRL key
• 16— Middle mouse button
Flags is the sum of all the buttons and keys that are
pressed
xpos Integer by value (the distance of the pointer from the left
edge of the window’s workspace in pixels)
ypos Integer by value (the distance of the pointer from the top of
the window’s workspace in pixels)
li_flags = flags
IF li_flags 15 THEN
// Middle button is pressed
lb_middle_button = TRUE
li_flags = li_flags - 16
280
Chapter 9 PowerScript Events
END IF
IF li_flags 7 THEN
// Control key is pressed
lb_control_key = TRUE
li_flags = li_flags - 8
END IF
// Set gauge
ocxitem.Object.Value = Round(ld_value, 0)
281
MouseMove
RETURN 1
Because the OCX also has a MouseMove event, this code in its MouseMove
event keeps the gauge responding when the pointer is over the gauge (you need
to pass values for the arguments the system ordinarily handles; the mouse
position values are specified in relation to the parent window):
Parent.EVENT MouseMove(0, Parent.PointerX(), &
Parent.PointerY())
See also Clicked
MouseDown
MouseUp
282
Chapter 9 PowerScript Events
MouseUp
The MouseUp event has different arguments for different objects:
Object See
RichTextEdit control Syntax 1
Window Syntax 2
Arguments None
Return codes Long. Return code choices (specify in a RETURN statement):
0 Continue processing
Usage A Clicked event also occurs when the mouse button is released.
Examples The following code in a RichTextEdit control’s MouseUp event assigns text to
the SingleLineEdit sle_1 when the user releases the left mouse button:
sle_1.Text = "Mouse Up"
See also Clicked
MouseDown
MouseMove
283
MouseUp
Arguments
Argument Description
flags UnsignedLong by value (the modifier keys and mouse
buttons that are pressed)
Values are:
• 1 — Left mouse button
• 2 — Right mouse button
• 4 — SHIFT key
• 8 — CTRL key
• 16 — Middle mouse button
In the MouseUp event, the left mouse button is being
released, so 1 is not summed in the value of flags
For an explanation of flags, see Syntax 2 of MouseMove
on page 279
xpos Integer by value (the distance of the pointer from the left
edge of the window’s workspace in pixels)
ypos Integer by value (the distance of the pointer from the top of
the window’s workspace in pixels)
CASE 4
sle_mkey.Text = "SHIFT key pressed"
CASE 8
sle_mkey.Text = "CONTROL key pressed"
284
Chapter 9 PowerScript Events
CASE 12
sle_mkey.Text = "SHIFT and CONTROL keys
pressed"
END CHOOSE
See also Clicked
MouseDown
MouseMove
285
Moved
Moved
Description Occurs when the user moves the scroll box, either by clicking on the arrows or
by dragging the box itself.
Event ID
Event ID Objects
pbm_sbnthumbtrack HScrollBar, HTrackBar, VScrollBar, VTrackBar
Arguments
Argument Description
scrollpos Integer by value (a number indicating position of the scroll
box within the range of values specified by the
MinPosition and MaxPosition properties)
286
Chapter 9 PowerScript Events
Open
The Open event has different arguments for different objects:
Object See
Application Syntax 1
Window Syntax 2
Arguments
Argument Description
commandline String by value
Additional arguments included on the command line after
the name of the executable program
On Windows
You can specify command line arguments when you use the Run command
from the Start menu or as part of the Target specification when you define a
shortcut for your application.
There is no way to specify command line values when you are testing your
application in the development environment.
In other events and functions, you can call the CommandParm function to get
the command line arguments.
For an example of parsing the string in commandline, see CommandParm on
page 405.
Examples This example populates the SQLCA global variable from the application’s
initialization file, connects to the database, and opens the main window:
287
Open
CONNECT;
Arguments None
Return codes Long. Return code choices (specify in a RETURN statement):
0 Continue processing
288
Chapter 9 PowerScript Events
When a window is opened, other events occur, such as Constructor for each
control in the window, Activate and Show for the window, and GetFocus for
the first control in the window’s tab order.
When a sheet is opened in an MDI frame, other events occur, such as Show and
Activate for the sheet and Activate for the frame.
Examples When the window contains a DataWindow control, you can retrieve data for it
in the Open event. In this example, values for the transaction object SQLCA
have already been set up:
dw_1.SetTransObject(SQLCA)
dw_1.Retrieve( )
See also Activate
Constructor
Show
289
Other
Other
Description Occurs when a system message occurs that is not a PowerBuilder message.
Event ID
Event ID Objects
pbm_other Windows and controls that can be placed in windows
Arguments
Argument Description
wparam UnsignedLong by value
lparam Long by value
290
Chapter 9 PowerScript Events
PageDown
Description Occurs when the user clicks in the open space below the scroll box.
Event ID
Event ID Objects
pbm_sbnpagedown VScrollBar, VTrackBar
Arguments None
Return codes Long. Return code choices (specify in a RETURN statement):
0 Continue processing
Usage When the user clicks in a vertical scrollbar, nothing happens unless you have
scripts that change the scrollbar’s Position property. For the scrollbar arrows,
use the LineUp and LineDown events; for clicks in the scrollbar background
above and below the thumb, use the PageUp and PageDown events; for
dragging the thumb itself, use the Moved event.
Examples Example 1 This code in the VScrollBar’s PageDown event uses a
predetermined paging value stored in the instance variable ii_pagesize to
change the position of the scroll box (you would need additional code to
change the view of associated controls according to the scrollbar position):
IF This.Position > &
This.MaxPosition - ii_pagesize THEN
This.Position = MaxPosition
ELSE
This.Position = This.Position + ii_pagesize
END IF
RETURN 0
Example 2 This example changes the position of the scroll box by a
predetermined page size stored in the instance variable ii_pagesize and scrolls
forward through a DataWindow control 10 rows for each page:
long ll_currow, ll_nextrow
ll_nextrow = ll_currow + 10
dw_1.ScrollToRow(ll_nextrow)
dw_1.SetRow(ll_nextrow)
See also LineDown
PageLeft
PageRight
PageUp
291
PageLeft
PageLeft
Description Occurs when the open space to the left of the scroll box is clicked.
Event ID
Event ID Objects
pbm_sbnpageup HScrollBar, HTrackBar
Arguments None
Return codes Long. Return code choices (specify in a RETURN statement):
0 Continue processing
Usage When the user clicks in a horizontal scrollbar, nothing happens unless you have
scripts that change the scrollbar’s Position property. For the scrollbar arrows,
use the LineLeft and LineRight events; for clicks in the scrollbar background
above and below the thumb, use the PageLeft and Right events; for dragging
the thumb itself, use the Moved event.
Examples This code in the PageLeft event causes the thumb to move left a predetermined
page size when the user clicks on the left arrow of the horizontal scrollbar (the
page size is stored in the instance variable ii_pagesize):
IF This.Position < &
This.MinPosition + ii_pagesize THEN
This.Position = MinPosition
ELSE
This.Position = This.Position - ii_pagesize
END IF
See also LineLeft
PageDown
PageRight
PageUp
292
Chapter 9 PowerScript Events
PageRight
Description Occurs when the open space to the right of the scroll box is clicked.
Event ID
Event ID Objects
pbm_sbnpagedown HScrollBar, HTrackBar
Arguments None
Return codes Long. Return code choices (specify in a RETURN statement):
0 Continue processing
Usage When the user clicks in a horizontal scrollbar, nothing happens unless you have
scripts that change the scrollbar’s Position property. For the scrollbar arrows,
use the LineLeft and LineRight events; for clicks in the scrollbar background
above and below the thumb, use the PageLeft and Right event; for dragging the
thumb itself, use the Moved event.
Examples This code in the PageRight event causes the thumb to move right when the user
clicks on the right arrow of the horizontal scrollbar (the page size is stored in
the instance variable ii_pagesize):
IF This.Position > &
This.MaxPosition - ii_pagesize THEN
This.Position = MaxPosition
ELSE
This.Position = This.Position + ii_pagesize
END IF
See also LineRight
PageDown
PageLeft
PageUp
293
PageUp
PageUp
Description Occurs when the user clicks in the open space above the scroll box (also called
the thumb).
Event ID
Event ID Objects
pbm_sbnpageup VScrollBar, VTrackBar
Arguments None
Return codes Long. Return code choices (specify in a RETURN statement):
0 Continue processing
Usage When the user clicks in a vertical scrollbar, nothing happens unless you have
scripts that change the scrollbar’s Position property. For the scrollbar arrows,
use the LineUp and LineDown events; for clicks in the scrollbar background
above and below the thumb, use the PageUp and PageDown events; for
dragging the thumb itself, use the Moved event.
Examples Example 1 This code in the PageUp event causes the thumb to move up when
the user clicks on the up arrow of the vertical scrollbar (the page size is stored
in the instance variable ii_pagesize):
IF This.Position < &
This.MinPosition + ii_pagesize THEN
This.Position = MinPosition
ELSE
This.Position = This.Position - ii_pagesize
END IF
Example 2 This example changes the position of the scroll box by a
predetermined page size stored in the instance variable ii_pagesize and scrolls
backwards through a DataWindow control 10 rows for each page:
long ll_currow, ll_prevrow
ll_currow = dw_1.GetRow( )
ll_prevrow = ll_currow - 10
dw_1.ScrollToRow(ll_prevrow)
dw_1.SetRow(ll_prevrow)
See also LineUp
PageDown
PageLeft
PageRight
294
Chapter 9 PowerScript Events
PictureSelected
Description Occurs when the user selects a bitmap in the RichTextEdit control by double-
clicking it or pressing ENTER after clicking it.
Event ID
Event ID Objects
pbm_renpictureselected RichTextEdit
Arguments None
Return codes Long. Return code choices (specify in a RETURN statement):
0 Continue processing
Examples When the user double-clicks a picture in a RichTextEdit control rte_1, the
picture is selected. This code for the PictureSelected event selects the rest of
the contents, copies the contents to a string with RTF formatting intact, and
pastes the formatted text into a second RichTextEdit rte_2:
string ls_transfer_rtf
This.SelectTextAll()
ls_transfer_rtf = This.CopyRTF()
rte_2.PasteRTF(ls_transfer_rtf)
See also InputFieldSelected
295
PipeEnd
PipeEnd
Description Occurs when pipeline processing is completed.
Event ID
Event ID Objects
pbm_pipeend Pipeline
Arguments None
Return codes Long. Return code choices (specify in a RETURN statement):
0 Continue processing
Usage You can use the PipeEnd event to check the status of pipeline processing.
The Start and Repair functions initiate pipeline processing.
For a complete example of using a Pipeline object, see Application Techniques.
Examples This code in a Pipeline user object’s PipeEnd event reports pipeline status in a
StaticText control:
ist_status.Text = "Finished Pipeline Execution ..."
See also PipeMeter
PipeStart
296
Chapter 9 PowerScript Events
PipeMeter
Description Occurs during pipeline processing after each block of rows is read or written.
The Commit factor specified for the Pipeline in the Pipeline painter determines
the size of each block.
Event ID
Event ID Objects
pbm_pipemeter Pipeline
Arguments None
Return codes Long. Return code choices (specify in a RETURN statement):
0 Continue processing
Usage The Start and Repair functions initiate pipeline processing.
In the Pipeline painter, you can specify a Commit factor specifying the number
of rows that will be transferred before they are committed to the database. The
PipeMeter event occurs for each block of rows as specified by the Commit
factor.
For a complete example of using a Pipeline object, see Application Techniques.
Examples This code in a Pipeline user object’s PipeMeter event report the number of rows
that have been piped to the destination database:
ist_status.Text = String(This.RowsWritten) &
+ " rows written to the destination database."
See also PipeEnd
PipeStart
297
PipeStart
PipeStart
Description Occurs when pipeline processing begins.
Event ID
Event ID Objects
pbm_pipestart Pipeline
Arguments None
Return codes Long. Return code choices (specify in a RETURN statement):
0 Continue processing
Usage You can use the PipeStart event to check the status of pipeline processing.
The Start and Repair functions initiate pipeline processing.
For a complete example of using a Pipeline object, see Application Techniques.
Examples This code in a Pipeline user object’s PipeStart event reports pipeline status in a
StaticText control:
ist_status.Text = "Beginning Pipeline Execution ..."
See also PipeEnd
PipeMeter
298
Chapter 9 PowerScript Events
PrintFooter
Description Occurs when the footer of a page of the document in the RichTextEdit control
is about to be printed.
Event ID
Event ID Objects
pbm_renprintfooter RichTextEdit
Arguments
Argument Description
currentpage Long by value (the number of the page being printed)
totalpages Long by value (the total number of pages in the document)
If the RichTextEdit control is sharing data with a
DataWindow, totalpages is the total number of pages in a
document instance
currentrow Long by value
If the RichTextEdit control is sharing data with a
DataWindow, then the number of the row associated with
the document instance currently being printed
299
PrintHeader
PrintHeader
Description Occurs when the header of a page of the document in the RichTextEdit control
is about to be printed.
Event ID
Event ID Objects
pbm_renprintheader RichTextEdit
Arguments
Argument Description
currentpage Long by value (the number of the page being printed)
totalpages Long by value (the total number of pages in the document)
If the RichTextEdit control is sharing data with a
DataWindow, totalpages is the total number of pages in a
document instance
currentrow Long by value
If the RichTextEdit control is sharing data with a
DataWindow, the number of the row associated with the
document instance currently being printed
300
Chapter 9 PowerScript Events
PropertyChanged
Description Occurs after the OLE server changes the value of a property of the OLE object.
Event ID
Event ID Objects
None OLE
Arguments
Argument Description
propertyname The name of the property whose value changed. If
propertyname is an empty string, a more general change
occurred, such as changes to more than one property
301
PropertyRequestEdit
PropertyRequestEdit
Description Occurs when the OLE server is about to change the value of a property of the
object in the OLE control.
Event ID
Event ID Objects
None OLE
Arguments
Argument Description
propertyname String by value (the name of the property whose value
changed)
If propertyname is an empty string, a more general
change occurred, such as changes to more than one
property
cancelchange Boolean by reference
Whether the change will be canceled. Values are:
• FALSE — (Default) The change is allowed
• TRUE — The change is canceled
302
Chapter 9 PowerScript Events
RButtonDown
The RButtonDown event has different arguments for different object:
Object See
Controls and windows, except Syntax 1
RichTextEdit
RichTextEdit control Syntax 2
Arguments
Argument Description
flags UnsignedLong by value (the modifier keys and mouse
buttons that are pressed)
Values are:
• 1 — Left mouse button
• 2 — Right mouse button
• 4 — SHIFT key
• 8 — CTRL key
• 16 — Middle mouse button
In the RButtonDown event, the right mouse button is
always pressed, so 2 is always summed in the value of
flags
For an explanation of flags, see Syntax 2 of MouseMove
on page 279
xpos Integer by value (the distance of the pointer from the left
edge of the window’s workspace in pixels)
ypos Integer by value (the distance of the pointer from the top
of the window’s workspace in pixels)
303
RButtonDown
Arguments None
Return codes Long. Return code choices (specify in a RETURN statement):
0 Continue processing
Usage If the control’s PopMenu property is TRUE, the standard RichTextEdit popup
menu is displayed instead, and the RButtonDown event does not occur.
You can use the RButtonDown event to implement your own popup menu.
See also Clicked
RButtonDown
304
Chapter 9 PowerScript Events
RButtonUp
Description Occurs when the right mouse button is released.
Event ID
Event ID Objects
pbm_renrbuttonup RichTextEdit
Arguments None
Return codes Long. Return code choices (specify in a RETURN statement):
0 Continue processing
1 Prevent processing
See also RButtonDown
305
RemoteExec
RemoteExec
Description Occurs when a DDE client application has sent a command.
Event ID
Event ID Objects
pbm_ddeexecute Window
Arguments None
Return codes Long. Return code choices (specify in a RETURN statement):
0 Continue processing
See also RemoteRequest
RemoteSend
306
Chapter 9 PowerScript Events
RemoteHotLinkStart
Description Occurs when a DDE client application wants to start a hot link.
Event ID
Event ID Objects
pbm_ddeadvise Window
Arguments None
Return codes Long. Return code choices (specify in a RETURN statement):
0 Continue processing
Examples When both the DDE client and server are PowerBuilder applications, this
example in a script in the client application will trigger the
RemoteHotLinkStart event in the server application window:
StartHotLink("mysle","pb_dde_server","mytest")
In the RemoteHotLinkStart event in the server application, set a boolean
instance variable indicating that a hot link has been established:
ib_hotlink = TRUE
See also HotLinkAlarm
RemoteHotLinkStop
SetDataDDE
StartServerDDE
StopServerDDE
307
RemoteHotLinkStop
RemoteHotLinkStop
Description Occurs when a DDE client application wants to end a hot link.
Event ID
Event ID Objects
pbm_ddeunadvise Window
Arguments None
Return codes Long. Return code choices (specify in a RETURN statement):
0 Continue processing
Examples When both the DDE client and server are PowerBuilder applications, this
example in a script in the client application will trigger the
RemoteHotLinkStop event in the server application window:
StopHotLink("mysle","pb_dde_server","mytest")
In the RemoteHotLinkStart event in the server application, set a boolean
instance variable indicating that a hot link no longer exists:
ib_hotlink = FALSE
See also HotLinkAlarm
RemoteHotLinkStart
SetDataDDE
StartServerDDE
StopServerDDE
308
Chapter 9 PowerScript Events
RemoteRequest
Description Occurs when a DDE client application requests data.
Event ID
Event ID Objects
pbm_dderequest Window
Arguments None
Return codes Long. Return code choices (specify in a RETURN statement):
0 Continue processing
See also RemoteExec
RemoteSend
309
RemoteSend
RemoteSend
Description Occurs when a DDE client application has sent data.
Event ID
Event ID Objects
pbm_ddepoke Window
Arguments None
Return codes Long. Return code choices (specify in a RETURN statement):
0 Continue processing
See also RemoteExec
RemoteRequest
310
Chapter 9 PowerScript Events
Rename
Description Occurs when the server application notifies the control that the object has been
renamed.
Event ID
Event ID Objects
pbm_omnrename OLE
Arguments None
Return codes Long. Return code: Ignored
Usage If you want to retrieve the ObjectData blob value of an OLE control during the
processing of this event, you must post a user event back to the control or you
will generate a runtime error.
See also DataChange
PropertyRequestEdit
PropertyChanged
ViewChange
311
Resize
Resize
Description Occurs when the user or a script opens or resizes the client area of a window or
DataWindow control.
Event ID
Event ID Objects
pbm_dwnresize DataWindow
pbm_size Window
Arguments
Argument Description
sizetype UnsignedLong by value
• 0 — (SIZE_RESTORED) The window or DataWindow
has been resized, but it was not minimized or
maximized. The user may have dragged the borders or
a script may have called the Resize function
• 1 — (SIZE_MINIMIZED) The window or
DataWindow has been minimized
• 2 — (SIZE_MAXIMIZED) The window or
DataWindow has been maximized
• 3 — (SIZE_MAXSHOW) This window is a popup
window and some other window in the application has
been restored to its former size (does not apply to
DataWindow controls)
• 4 — (SIZE_MAXHIDE) This window is a popup
window and some other window in the application has
been maximized (does not apply to DataWindow
controls)
newwidth Integer by value (the width of the client area of a window
or DataWindow control in PowerBuilder units)
newheight Integer by value (the height of the client area of a window
or DataWindow control in PowerBuilder units)
312
Chapter 9 PowerScript Events
RightClicked
The RightClicked event has different arguments for different objects:
Object See
ListView and Tab control Syntax 1
TreeView control Syntax 2
ProgressBar control Syntax 3
Arguments
Argument Description
index Integer by value (the index of the item or tab the user
clicked)
313
RightClicked
RightDoubleClicked
Arguments
Argument Description
handle Long by value (the handle of the item the user clicked)
Arguments None
314
Chapter 9 PowerScript Events
315
RightDoubleClicked
RightDoubleClicked
The RightDoubleClicked event has different arguments for different objects:
Object See
ListView and Tab control Syntax 1
TreeView control Syntax 2
Arguments
Argument Description
index Integer by value (the index of the item or tab the user
double-clicked)
IF li_rtn = 1 THEN
This.Arrange( )
ELSE
MessageBox("Error", Deletion failed!")
END IF
See also DoubleClicked
RightClicked
316
Chapter 9 PowerScript Events
Arguments
Argument Description
handle Long by value (the handle of the item the user double-
clicked)
317
Save
Save
Description Occurs when the server application notifies the control that the data has been
saved.
Event ID
Event ID Objects
pbm_omnsave OLE
Arguments None
Return codes Long. Return code: Ignored
Usage If you want to retrieve the ObjectData blob value of an OLE control during the
processing of this event, you must post a user event back to the control or you
will generate a runtime error.
Examples In this example, a table in a database tracks changes of OLE objects; when the
user saves an Excel spreadsheet in an OLE control, this code puts the current
date in a DataWindow so that the database table can be updated:
long ll_row
// Find the row with information for the Excel file
ll_row = dw_1.Find("file_name = ’expenses.xls’", &
1, 999)
318
Chapter 9 PowerScript Events
SaveObject
Description Occurs when the server application saves the object in the control.
Event ID
Event ID Objects
pbm_omnsaveobject OLE
Arguments None
Return codes Long. Return code: Ignored
Usage Using the SaveObject event is the preferred technique for retrieving the
ObjectData blob value of an OLE control when the server saves the data in the
embedded object. Unlike the Save and Close events, the SaveObject event does
not require you to post a user event back to the control to prevent the generation
of a runtime error.
Because of differences in the behavior of individual servers, this event is not
triggered consistently across all server applications. Using Microsoft Word 97
or Excel 97, the SaveObject event is triggered when the DisplayType property
of the control is set to DisplayAsActiveXDocument! or DisplayAsIcon!, but
not when it is set to DisplayAsContent!. For other applications, such as Paint
Shop Pro 4, the event is triggered when the display type is DisplayAsContent!
but not when it is DisplayAsActiveXDocument!.
Because some servers may also fire the PowerBuilder Save event and the
relative timing of the two events cannot be guaranteed, your program should
only handle the SaveObject event.
Examples In this example, when the user or the server application saves a Word document
in an OLE control, the data is saved as a blob in a file. The file can then be
opened as a Word document:
blob l_myobjectdata
l_myobjectdata = this.objectdata
integer l_file
319
Selected
Selected
Description Occurs when the user highlights an item on the menu using the arrow keys or
the mouse, without choosing it to be executed.
Event ID
Event ID Objects
None Menu
Arguments None
Return codes None (do not use a RETURN statement)
Usage You can use the Selected event to display MicroHelp for the menu item. One
way to store the Help text is in the menu item’s Tag property.
Examples This example uses the tag value of the current menu item to display Help text.
The function wf_SetMenuHelp takes the text passed (the tag) and assigns it to
a MultiLineEdit control. A Timer function and the Timer event are used to clear
the Help text.
This code in the Selected event calls the function that sets the text:
w_test.wf_SetMenuHelp(This.Tag)
This code for the wf_SetMenuHelp function sets the text in the MultiLineEdit
mle_menuhelp; its argument is called menuhelpstring:
mle_menuhelp.Text = menuhelpstring
Timer(4)
This code in the Timer event clears the Help text and stops the timer:
w_test.wf_SetMenuHelp("")
Timer(0)
See also Clicked
320
Chapter 9 PowerScript Events
SelectionChanged
The SelectionChanged event has different arguments for different objects:
Object See
DropDownListBox, Syntax 1
DropDownPictureListBox, ListBox,
PictureListBox controls
Tab control Syntax 2
TreeView control Syntax 3
Arguments
Argument Description
index Integer by value (the index of the item that has become
selected)
321
SelectionChanged
integer itemcount,i,r
string ls_colname
gr_1.SetRedraw(FALSE)
NEXT
gr_1.SetRedraw(TRUE)
See also Clicked
Arguments
Argument Description
oldindex Integer by value (the index of the tab that was previously
selected)
newindex Integer by value (the index of the tab that has become
selected)
322
Chapter 9 PowerScript Events
Usage The SelectionChanged event occurs when the Tab control is created and the
initial selection is set.
See also Clicked
SelectionChanging
Arguments
Argument Description
oldhandle Long by value (the handle of the previously selected item)
newhandle Long by value (the handle of the currently selected item)
323
SelectionChanging
SelectionChanging
The SelectionChanging event has different arguments for different objects:
Object See
Tab control Syntax 1
TreeView control Syntax 2
Arguments
Argument Description
oldindex Integer by value (the index of the currently selected tab)
newindex Integer by value (the index of the tab that is about to be
selected)
luo_Tab = This.Control[newindex]
luo_Tab.dw_dir.Height = dw_list.Height
luo_Tab.dw_dir.Width = dw_list.Width
324
Chapter 9 PowerScript Events
Arguments
Argument Description
oldhandle Long by value (the handle of the currently selected item)
newhandle Long by value (the handle of the item that is about to be
selected)
325
Show
Show
Description Occurs just before the window is displayed.
Event ID
Event ID Objects
pbm_showwindow Window
Arguments
Argument Description
show Boolean by value (whether the window is being shown)
The value is always TRUE.
status Long by value (the status of the window)
Values are:
• 0 — The current window is the only one affected
• 1 — The window’s parent is also being minimized or a
popup window is being hidden
• 3 — The window’s parent is also being displayed or
maximized or a popup window is being shown
326
Chapter 9 PowerScript Events
Sort
The Sort event has different arguments for different objects:
Object See
ListView control Syntax 1
TreeView control Syntax 2
Arguments
Argument Description
index1 Integer by value (the index of one item being compared
during a sorting operation)
index2 Integer by value (the index of the second item being
compared)
column Integer by value (the number of the column containing the
items being sorted)
327
Sort
This.GetItem(index1, lvi)
This.GetItem(index2, lvi2)
Arguments
Argument Description
handle1 Long by value (the handle of one item being compared
during a sorting operation)
handle2 Long by value (the handle of the second item being
compared)
328
Chapter 9 PowerScript Events
The Sort event occurs if you call the Sort event, or when you call the Sort
function using the UserDefinedSort! argument.
Examples This example sorts TreeView items according to PictureIndex and Label
sorting by PictureIndex first then by label:
TreeViewItem tvi, tvi2
This.GetItem(handle1, tvi)
This.GetItem(handle2, tvi2)
329
SystemError
SystemError
Description Occurs when a serious execution time error occurs (such as trying to open a
nonexistent window) if the error is not handled in a TRY-CATCH block.
Event ID
Event ID Objects
None Application
Arguments None
Return codes None (do not use a RETURN statement)
Usage If there is no script for the SystemError event, PowerBuilder displays a
message box with the PowerBuilder error number and error message text.
For information about error messages, see the PowerBuilder User’s Guide.
You can prevent the SystemError event from occuring by handling errors in
TRY-CATCH blocks. Well-designed exception-handling code gives
application users a better chance to recover from error conditions and run the
application without interruption.
For information about exception handling, see Application Techniques.
Previously, for errors involving external objects and DataWindows, you could
handle the error in the ExternalException or Error events and prevent the
SystemError event from occurring. The ExternalException and Error events
are maintained for backward compatibily only.
When a SystemError event occurs, your current script terminates and your
system may become unstable. It is generally not a good idea to continue
running the application, but you can use the SystemError event script to clean
up and disconnect from the DBMS before closing the application.
Examples This statement in the SystemError event halts the application immediately:
HALT CLOSE
See also Error
ExternalException
TRY...CATCH...FINALLY...END TRY
330
Chapter 9 PowerScript Events
SystemKey
Description Occurs when the insertion point is not in a line edit and the user presses the ALT
key (alone or with another key).
Event ID
Event ID Objects
pbm_syskeydown Window
Arguments
Argument Description
key KeyCode by value
A value of the KeyCode enumerated data type indicating the key that
was pressed, for example, KeyA! or KeyF1!
keyflags UnsignedLong by value (the modifier keys that were pressed with the
key). The only modifier key is:
1 SHIFT key
CASE KeyF1!
ls_key = "F1"
CASE KeyA!
ls_key = "A"
CASE KeyF2!
ls_key = "F2"
END CHOOSE
This example causes a beep if the user presses ALT+SHIFT+F1.
IF keyflags = 1 THEN
IF key = KeyF1 THEN
Beep(1)
END IF
END IF
See also Key
331
Timer
Timer
Description Occurs when a specified number of seconds elapses after the Start or Timer
function has been called.
Event ID
Event ID Objects
pbm_timer Timing or Window
Arguments None
Return codes Long. Return code choices (specify in a RETURN statement):
0 Continue processing
Examples These examples show how to use a timing object’s Timer event and a window’s
Timer event.
Using a timing object This example uses a timing object to refresh a list of
customers retrieved from a database at specified intervals. The main window
of the application, w_main, contains a DataWindow control displaying a list of
customers and two buttons, Start Timer and Retrieve. The window’s Open even
connects to the database:
CONNECT using SQLCA;
332
Chapter 9 PowerScript Events
The timing object’s Timer event calls an object-level function that refreshes the
datastore:
refresh_custlist()
Here’s refresh_custlist():
long ll_rowcount
ds_datastore.dataobject = "d_customers"
ds_datastore.SetTransObject (SQLCA)
ll_rowcount = ds_datastore.Retrieve()
RETURN ll_rowcount
The Retrieve button on w_main simply shares the data from the DataStore with
the DataWindow control:
ds_datastore.ShareData(dw_1)
Using a window object This example causes the current time to be
displayed in a StaticText control in a window. Calling Timer in the window’s
Open event script starts the timer. The script for the Timer event refreshes the
displayed time.
In the window’s Open event script, this code displays the time initially and
starts the timer:
st_time.Text = String(Now(), "hh:mm")
Timer(60)
In the window’s Timer event, which is triggered every minute, this code
displays the current time in the StaticText st_time:
st_time.Text = String(Now(), "hh:mm")
333
ToolbarMoved
ToolbarMoved
Description Occurs in an MDI frame window when the user moves any FrameBar or
SheetBar.
Event ID
Event ID Objects
pbm_tbnmoved Window
Arguments None
Return codes Long. Return code choices (specify in a RETURN statement):
0 Continue processing
Usage The event is not triggered for sheet windows.
To get information about the toolbars’ positions, call the GetToolbar and
GetToolbarPos functions.
This event occurs when you change a toolbar’s position with SetToolbarPos.
334
Chapter 9 PowerScript Events
ViewChange
Description Occurs when the server application notifies the control that the view shown to
the user has changed.
Event ID
Event ID Objects
pbm_omnviewchange OLE
Arguments None
Return codes Long. Return code: Ignored
Usage If you want to retrieve the ObjectData blob value of an OLE control during the
processing of this event, you must post a user event back to the control or you
will generate a runtime error.
See also DataChange
PropertyRequestEdit
PropertyChanged
Rename
335
ViewChange
336
Index
Index-1
Index
Index-2
Index
bitmaps cancellation
assigning to picture control 1088 allowing 1239
in rich text 692 of edits 1222
printing 901 of pipeline object 374
retrieving from clipboard 389 of printing 902
blob data type 24 CanUndo function 375
Blob function 367 capitalization
blob functions in category names 342, 667
Blob 367 in series names 355
BlobEdit 368 lowercase 761
BlobMid 369 uppercase 1226
Len 732 caret in text patterns 783
BlobEdit function 368 carriage return
BlobMid function 369 in INI files 936
blobs specifying 9
assigning to picture control 1088 cascaded windows, arranging sheets 360
converting to string 367, 1166 cascading opened windows 831
declaring 40 case sensitivity, comparisons 72
extracting values from 439, 444, 451, 695, 754, categories, graphs
943, 1185 adding data values to series 342, 345
inserting data into 368 adding to a series 342
reading streams into 941 clicked 809
selecting from database 172 counting 376
updating 175 deleting 452, 963
writing to stream 1237 identifying 376, 377
boolean data type 24 importing data 646, 648, 651
border InsertCategory function 342
determining distance from 872, 873 inserting 667
printing 914, 917, 919 new 342
bottom layer of DataWindow 1091 CategoryCount function 376
bound 762, 1227 CategoryName function 377
brackets in text patterns 784 Ceiling function 378
BuildModel function 371 century 1238
ChangeDirectory function 379
ChangeMenu function 380
channel, DDE 396, 829
C char data type
C functions about 24
decoding returned values 698, 699 array 79
passing values to 754 converting to string 78
CALL statement Char function 381
about 127 character array 1237
not using 194 characters
Cancel button 790 array 941
Cancel function 374 changing capitalization 761, 1226
converting to ASCII values 361
Index-3
Index
Index-4
Index
Index-5
Index
Index-6
Index
Index-7
Index
Index-8
Index
Index-9
Index
Index-10
Index
events F
about 94, 194
Fact function 495
adding to queue 886
FETCH statement 166
ancestor 117
file functions
and hidden objects 640
FileClose 496
and print jobs 904
FileDelete 498
arguments 108, 194
FileExists 499
cascaded calls 111, 114
FileLength 500
defined 94
FileOpen 502
errors when calling 103
FileRead 504
extending 107
FileSeek 507
finding 97
FileWrite 508
overriding 107
GetFileOpenName 584
posting 98, 112, 1180
GetFileSaveName 586
return codes 195
FileClose function 496
return values 111, 195
FileCopy function 497
similarities to functions 95
FileDelete function 498
static and dynamic 100
FileExists event 250
system 94, 194
FileExists function 499
triggering 98, 194, 1181, 1209
FileLength function 500
user-defined 194, 195
FileMove function 501
exclamation point icon 790
FileOpen function 502
exclusive share mode 821, 824
FileRead function 504
ExecRemote function 489
files
executable
importing data from 648
returning application handle 638
linking 749
running 987
security and sharing violation 500
EXECUTE statement 165, 1067
FileSeek function 507
execution errors 102
FileWrite function 508
EXIT statement 138
Fill function
Exp function 492
about 510
ExpandAll function 493
and printing 510
ExpandItem function 494
FillPattern 570, 1063, 1107
exponent 492
filtering filenames 584, 586
exponentiation operator 70
Find function 511
expressions
FindCategory function 513
Any data type 30
FindClassDefinition function 515
checking for NULL 717
FindFunctionDefinition function 516
data type promotion 76
FindItem function 517
data types 76
FindMatchingFunction function 523
DataWindows and Any data type 31
FindNext function 525
in declaration 43
FindSeries function 526
literals 77
FindTypeDefinition function 527
operators and data types 76
flicker 1098
external functions 60
focus
ExternalException event 247
and line length 747
Index-11
Index
Index-12
Index
Index-13
Index
Index-14
Index
Index-15
Index
Index-16
Index
Index-17
Index
Index-18
Index
Index-19
Index
Index-20
Index
Index-21
Index
Index-22
Index
Index-23
Index
Index-24
Index
Index-25
Index
Index-26
Index
Index-27
Index
Index-28
Index
Index-29
Index
Index-30
Index
Index-31
Index
Index-32
Index
Index-33
Index
W
warm link 489, 614, 829, 1101
V week, day of 446, 447
value, passing arguments by 108 Which function 1229
values white space 21
adding to lists 348 width
checking for NULL 717 data point’s line 1062
data points 574 series line 1106
deleting from list 456 setting 968
detecting numeric 718 string 931
inserting into lists 677 workspace 1234
variables Window ActiveX controls
access levels 45 GetArgElement function 538
assigning literals 24, 25, 26, 28 GetLastReturn function 598
assigning values 43 InvokePBFunction function 700
checking for NULL 717 ResetArgElements function 965
data type 41 SetArgElement function 1042
declaring 36 TriggerPBEvent function 1211
declaring initial values 42 Window functions
default values 42 ArrangeSheets 360
determining data type of 385 ChangeMenu 380
extracting data from a blob 369 ClassName 385
host 152 CloseUserObject 399
indicator 152 Draw 483
initializing with expression 43 GetActiveSheet 535
inserting data into a blob 368 GetFirstSheet 588
names 42 GetNextSheet 605
OLEObject 414 Hide 640
referencing in SQL 152 Move 802
search order 37 Open 814
setting to NULL 11, 1084 OpenSheet 831
validating 725 OpenSheetWith Parm 833
where to declare 36 OpenTab 836
variable-size arrays, memory allocation 54, 1227 OpenUserObject 845
vertical fill pattern 1064, 1108 OpenWith Parm 854
video monitor 583 ParentWindow 863
ViewChange event 335 PointerX 872
PointerY 873
Index-34
Index
Index-35