Powerscript Reference v2019r3
Powerscript Reference v2019r3
1 PowerScript Topics
This part describes the basics of using the PowerScript language.
1.1.1 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
The following table shows how to use each method.
• Can be nested
Page 33
PowerScript Topics
For information about adding comments to objects and library entries, see the
Section 2.2.4.13, “Modifying comments” in Users Guide.
Examples
Double-slash method
// This entire line is a comment.
// This entire line is another comment.
amt = qty * cost // Rest of the line is comment.
Slash-and-asterisk method
/* This is a single-line comment. */
• Are not case sensitive (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
Page 34
PowerScript Topics
By default, PowerBuilder allows you to use dashes in all identifiers, including in variable
names in a script. However, 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. As a result, 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.
Examples
Valid identifiers
ABC_Code
Child-Id
FirstButton
response35
pay-before%deductions$
ORDER_DATE
Actual-$-amount
Part#
Invalid identifiers
2nd-quantity // Does not start with a letter
ABC Code // Contains a space
Child'sId // Contains invalid special character
1.1.3 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. For information about valid
identifiers, see Identifier names.
Examples
On a line by itself above the statement
FindCity:IF city=cityname[1] THEN ...
Page 35
PowerScript Topics
Examples
Entering ASCII characters
Here is how to use special characters in strings:
Table 1.3:
String Description
"dog~n" A string containing the word dog followed by
a newline character
Page 36
PowerScript Topics
String Description
"dog~tcat~ttiger" A string containing the word dog, a tab
character, the word cat, another tab character,
and the word tiger
Table 1.4:
Value Description
"~249" The ASCII character with decimal value 249
"~hF9" The ASCII character with hexadecimal value
F9
"~o371" The ASCII character with octal value 371
• 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.
Note
Null in a variable
When a null value is read into a variable, the variable remains null unless it is
changed in a script.
• The SetNull function is used in a script to set the variable explicitly to null. For example:
string city // city is an empty string.
Page 37
PowerScript Topics
Invalid
This statement shows the incorrect way to test for null:
IF a = NULL THEN ...
Examples
Example 1
None of the following statements make the computer beep (the variable nbr is set to null, so
each statement evaluates to false):
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 false, 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 false, and the ELSE is executed:
IF GetFocus( ) THEN
. . . // Some processing
ELSE
MessageBox("Important", "Specify an option!")
END IF
Page 38
PowerScript Topics
The PowerBuilder system class also includes private variables that you cannot use as
identifiers. If you use a private variable as an identifier, you get an informational message
and should rename your identifier.
Page 39
PowerScript Topics
If you are deploying a DataWindow to the Web, you cannot use JavaScript reserved words
to name fields or bands in the DataWindow object. The list of reserved words is available at
https://docs.microsoft.com/en-us/scripting/javascript/reference/javascript-reserved-words.
1.1.7 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.
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:
The following table lists the PowerScript pronouns and summarizes their use.
Table 1.6: PowerScript pronouns
This In a script for a Refers to the
pronoun
This Window, custom user object, menu, Object or control itself
application object, or control
Parent Control in a window Window containing the control
Control in a custom user object Custom user object containing the control
Menu Item in the menu on the level above the
current menu
Super descendant object or control Parent
descendant window or user object Immediate ancestor of the window or user
object
Control in a descendant window or user Immediate ancestor of the control's parent
object window or user object
ParentWindow property
You can use the ParentWindow property of the Menu object like a pronoun in Menu scripts.
It identifies the window that the menu is associated with when your program is running. For
more information, see the Section 4.6.6.3, “Referring to objects in your application” in Users
Guide.
The rest of this section describes the individual pronouns in detail.
Page 40
PowerScript Topics
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
• Menus
If you include this statement in the script for the CommandButton, clicking the button
displays a horizontal scroll bar within the window (sets the HScrollBar property of the
window to true):
Parent.HScrollBar = TRUE
If you include this statement in the script for the CheckBox, clicking the check box 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( )
Page 41
PowerScript Topics
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
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). It refers to
the object's X property if there is no local variable:
x = x + 50
Example 4
Use This to ensure that you refer to the property. For example, in the following statement
in the script for the Clicked event for a CommandButton, clicking the button changes the
horizontal position of the button (changes the button's X property):
Page 42
PowerScript Topics
This.x = This.x + 50
This example must be part of a script or function in the descendant window, not one of the
window's controls. For example, if it is in the Clicked event of a button on the descendant
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.
Example 2
This example in a CommandButton script calls the Clicked script for the CommandButton in
the immediate ancestor window or user object:
Super::EVENT Clicked()
Page 43
PowerScript Topics
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.
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.
Examples
Continuing a quoted string
One way
Place an ampersand in the middle of the string and continue 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
The following 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 might result in an error:
IF Employee_District = "Eastern United States and&
Eastern Canada" THEN ...
A better way
A better way to continue a quoted string is to enter a quotation mark before the continuation
character ('& or "&, depending on whether the string is delimited by single or double
quotation marks) at the end of the first line of the string and a plus sign and a quotation mark
(+' or +") at the start of the next line. This way, you do not inadvertently include unwanted
characters (such as tabs or spaces) in the string literal:
IF Employee_District = "Eastern United States and "&
+" Eastern Canada" THEN ...
Page 44
PowerScript Topics
The examples in the PowerBuilder documentation use this method to continue quoted strings.
Continuing a variable name
Do not split a line by inserting the continuation character within a variable name. This causes
an error and the statement fails, because the continuation character splits the variable name
"Quantity":
Total-Cost = Price * Quan&
tity + (Tax + Shipping)
Examples
The following line contains three short statements:
A = B + C; D = E + F; Count = Count + 1
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:
Page 45
PowerScript Topics
Table 1.7:
Parameter Description
predefined_symbols
A predefined identifier or a combination of predefined identifiers separated
by AND or OR operators. In the current release, you cannot use a user-
defined identifier.
action1, The action you want performed if the condition in the previous statement
action2, was met.
action3
Usage
Conditional compilation enables you to include PowerScript code for a specific target type or
set of target types in an application. You can also include debug code in your application and
specify in the Project painter whether it will be included in your application's executable file.
The preprocessor substitutes blank lines for statements with a leading number (#) sign
character. It passes the code in the action statements to the compiler or converts it to blank
lines depending on whether the condition in the previous preprocessor directive was met.
The following table displays the predefined symbols, the project types to which they
correspond, and their effects on the code passed to the compiler.
Page 46
PowerScript Topics
You can use the NOT operator to include code for all target types that are not of the type
that you specify, and you can use AND and OR operators to combine symbols. For example,
code that follows this statement will be parsed for all targets except standard PowerBuilder
applications:
#if NOT defined PBNATIVE then
Comments can be added to conditional code blocks if they are preceded by double slash
marks ( // ) in the same line of code. You cannot use the PowerScript line continuation
character ( & ) in a conditional code statement. You must use it in code that you embed in the
conditional block when you use more than one line for a single line of code.
Limitations and error messages
Conditional compilation is not supported in DataWindow syntax, or in structure or menu
objects. You cannot edit the source code for an object to include conditional compilation
blocks that span function, event, or variable definition boundaries.
You must rebuild your application after you add a DEBUG conditional block.
The following table shows the types of error messages displayed for incorrect conditional
compilation code.
Examples
When you run or debug the application in the development environment, the following code
is always parsed and you always see the message box. When you run the executable file,
the code is parsed only if the DEBUG symbol is enabled on the General page in the Project
painter:
#if defined DEBUG then
MessageBox("Debugging","Ctr value is " + string(i))
#end if
Page 47
PowerScript Topics
1.2 Datatypes
About this chapter
This chapter describes the PowerScript datatypes.
Table 1.10:
Blob LongLong
Boolean Long
Byte Longptr
Char or character Real
Date String
DateTime Time
Decimal or Dec UnsignedInteger, UnsignedInt, or UInt
Double UnsignedLong or ULong
Integer or Int
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.
Byte
8-bit unsigned integers, from 0 to +255.
Using literals
To assign a literal value, use any whole positive number in the range 0 to 255. The leading
plus sign is not required (18 and +18 are the same). For example:
1 123 200 +55 +200
Char or character
A single Unicode 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 might want to
use char arrays instead of strings.
Page 48
PowerScript Topics
For more information about passing character-based data to external functions, see
Section 5.5.1, “Using external functions” in Application Techniques. For information about
datatype conversion when assigning strings to chars and vice versa, see String and char
datatypes in PowerBuilder.
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:
2001-12-25 // December 25, 2001
2003-02-06 // February 6, 2003
DateTime
The date and time in a single datatype, used only for reading and writing DateTime values
from and to a database. To convert DateTime values to datatypes that you can use in
PowerBuilder, use:
• The DateTime (date, time) function to convert a date and (optional) time to a DateTime
before writing to a DateTime column in a database.
PowerBuilder supports microseconds in the database interface for any DBMS that supports
microseconds.
Decimal or Dec
Signed decimal numbers, positive or negative, with up to 28 digits. You can
place the decimal point anywhere within the 28 digits -- for example, 123.456,
0.000000000000000000000001 or 12345678901234.5678901234.
Using literals
To assign a literal value, use any number with a decimal point and no exponent. The plus sign
is optional (95 and +95 are the same). For numbers between zero and one, the zero to the left
of the decimal point is optional (for example, 0.1 and .1 are the same). For whole numbers,
zeros to the right of the decimal point are optional (32.00, 32.0, and 32. are all the same). For
example:
12.34 0.005 14.0 -6500 +3.5555
Page 49
PowerScript Topics
Double
A signed floating-point number with 15 digits of precision and a range from
2.2250738585073E-308 to 1.79769313486231E+308, and -2.2250738585073E-308 to
-1.79769313486231E+308.
Integer or Int
16-bit signed integers, from -32768 to +32767.
Using literals
To assign a literal value, use any whole number (positive, negative, or zero). The leading plus
sign is optional (18 and +18 are the same). For example:
1 123 1200 +55 -32
Long
32-bit signed integers, from -2147483648 to +2147483647.
Using literals
Use literals as for integers, but longer numbers are permitted.
LongLong
64-bit signed integers, from -9223372036854775808 to 9223372036854775807.
Using literals
Use literals as for integers, but longer numbers are permitted.
Longptr
4 bytes in the 32-bit platform and 8 bytes in the 64-bit platform.
Using literals
In the 32-bit platform, longptr is the same as long; you can continue using long wherever
longptr is required in 32-bit applications. In 64-bit applications, however, using long to hold
longptr variables will lead to data truncation from 8 bytes to 4 bytes, or memory corruption if
you pass a long ref variable when a longptr ref is required. If you want to move to 64-bit, use
longptr wherever required. It does no harm to 32-bit.
Real
A signed floating-point number with six digits of precision and a range from 3.402822E-38 to
3.402822E+38, and -3.402822E-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.5E38 +6.02E3 -4.1E-2
-7.45E16 7.7E+8 3.2E-38
String
Any string of Unicode characters with variable length (0 to 1073741823).
Page 50
PowerScript Topics
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
Section 5.5.1, “Using external functions” in Application Techniques. For information about
datatype conversion when assigning strings to chars and vice versa, see String and char
datatypes in PowerBuilder.
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, the following statements result in the string Here's a string:
string s1
s1 = "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.
Example 1
This string has two levels of nesting:
"He said ~"she said ~~~"Hi ~~~" ~" "
Example 2
A more probable example is a string for the Modify function that sets a DataWindow
property. The argument string often requires complex quotation marks (because you must
specify one or more levels of nested strings). To understand the quotation marks, consider
how PowerBuilder will parse the string. The following string is a possible argument for the
Modify function; it mixes single and double quotes to reduce the number of tildes:
Page 51
PowerScript Topics
"bitmap_1.Invert='0~tIf(empstatus=~~'A~~',0,1)'"
The double quotes tell PowerBuilder to interpret the argument as a string. It contains the
expression being assigned to the Invert property, which is also a string, so it must be quoted.
The expression itself includes a nested string, the quoted A. First, PowerBuilder evaluates the
argument for Modify and assigns the single-quoted string to the Invert property. In this pass
through the string, it converts two tildes to one. The string assigned to Invert becomes:
'0[tab]If(empstatus=~'A~',0,1)'
• A tilde tells the parser that the next character should be taken as a literal, not a string
terminator
• 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 the fractions of seconds, 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
Page 52
PowerScript Topics
• You must know the content of an Any variable to make assignments from the Any variable
to a compatible datatype.
Restrictions
If the value of a simple Any variable is an array, you cannot access the elements of the array
until you assign the value to an array variable of the appropriate datatype. This restriction
does not apply to the opposite case of an array of Any variables -- you can access each Any
variable in the array.
If the value of an Any variable is a structure, you cannot use dot notation to access the
elements of the structure until you assign the value to a structure of the appropriate datatype.
After a value has been assigned to an Any variable, it cannot be converted back to a generic
Any variable without a datatype. Even if you set it to NULL, it retains the datatype of the
assigned value until you assign another value.
Operations and expressions
You can perform operations on Any variables as long as the datatype of the data in the Any
variable is appropriate to the operator. If the datatype is not 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
Page 53
PowerScript Topics
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.
Datatype conversion functions
PowerScript datatype 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 datatype for an argument, you cannot use
an Any variable without a conversion function, even if it contains a value of the correct
datatype. When you compile the script, you 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
This works because the string value of the Any expression is explicitly converted to a string:
IF Len(String(dw_notes.Object.Notes[1])) > 0 THEN
The objects these expressions point to can change so that the type of data being accessed also
changes.
Expressions that refer to DataWindow data can return arrays and structures and arrays of
structures as Any variables. For best performance, assign the DataWindow expression to the
appropriate array or structure without using an intermediate Any variable.
Overusing the Any datatype
Do not use Any variables as a substitute for selecting the correct datatype in your scripts.
There are two reasons for this:
Page 54
PowerScript Topics
• At compile time, using Any variables removes a layer of error checking from your
programming
The PowerBuilder compiler makes sure datatypes are correct before code gets executed.
With Any variables, some of the errors that can be caught by the compiler are not found
until the code is run.
If you have a series of buttons in a window and need to keep track of one of them (such as
the last one clicked), you can declare a variable of type CommandButton and assign it the
appropriate button in the window:
// Instance variable in a window
commandbutton LastClicked
// In Clicked event for a button in the window.
// Indicates that the button was the last one
// clicked by the user.
LastClicked = This
Page 55
PowerScript Topics
To learn more about working with instances of objects through datatypes, see About objects.
• As arguments in functions
You can list all the enumerated datatypes and their values by selecting the Enumerated tab in
the Browser.
You cannot create your own enumerated datatypes. As an alternative, you can declare a set of
constant variables and assign them initial values. See Declaring constants.
A variable of one of the enumerated datatypes can be assigned a fixed set of values. Values of
enumerated datatypes always end with an exclamation point (!). For example, the enumerated
datatype Alignment, which specifies the alignment of text, can be assigned one of the
following three values: Center!, Left!, and Right!:
mle_edit.Alignment=Right!
Incorrect syntax
Do not enclose an enumerated datatype value in quotation marks. If you do, you
receive a compiler error.
1.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).
Page 56
PowerScript Topics
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.
1. Select Declare from the first drop-down list in the Script view.
2. Select the type of variable you want to declare in the second drop-down list 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 cursors
You can also declare SQL cursors that are global, shared, instance, or local. 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 pop-up menu.
Page 57
PowerScript Topics
1. A local variable
2. A shared variable
3. A global variable
4. An instance variable
As soon as PowerBuilder finds a variable with the specified name, it uses the variable's value.
Referring to global variables
To refer to a global variable, you specify its name in a script. However, if the 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 ...
• 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
Page 58
PowerScript Topics
• 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 as follows:
sle_id.Text = EmpID
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
There is another situation in which references must be qualified. Suppose that w_emp has
an instance variable EmpID and that in w_emp there is a CommandButton that declares a
local variable EmpID in its Clicked script. In that script, you must qualify all references to the
instance variable:
Parent.EmpID
Page 59
PowerScript Topics
Naming errors
If a local or global variable exists with the name "index", then the unqualified name refers
to the local or global variable. It is a programming error if you meant to refer to the object
variable. You get an informational message from the compiler if you use the same name for
instance and global variables.
Full syntax
The full syntax allows you to specify access and an initial value. Arrays and some datatypes,
such as blobs and decimals, accept additional information:
{ access } datatype { { size } } { { precision } } variablename { = value }
{, variablename2 { = value2 } }
Page 60
PowerScript Topics
Examples
Declaring instance variables
integer ii_total = 100 // Total shares
date id_date // Date shares were bought
Declaring blobs
This statement declares ib_Emp_Picture a blob with an initial length of zero. The length is
adjusted when data is assigned to it:
blob ib_Emp_Picture
This statement declares ib_Emp_Picture a blob with a fixed length of 100 bytes:
blob{100} ib_Emp_Picture
Declaring decimals
These statements declare shared variables sc_Amount and sc_dollars_accumulated as
decimal numbers with two digits after the decimal point:
decimal{2} sc_Amount
decimal{2} sc_dollars_accumulated
This statement declares lc_Rate1 and lc_Rate2 as decimal numbers with four digits after the
decimal point:
dec{4} lc_Rate1, lc_Rate2
This statement declares lc_Balance as a decimal with zero digits after the decimal point:
decimal{0} lc_Balance
This statement does not specify the number of decimal places for lc_Result. After the product
of lc_Op1 and lc_Op2 is assigned to it, lc_Result has four decimal places:
dec lc_Result
dec{2} lc_Op1, lc_Op2
lc_Result = lc_Op1 * lc_Op2
Page 61
PowerScript Topics
• An object or structure that you have defined (such as a window called mywindow). An
object you have defined must be in a library on the application's library search path when
the script is compiled.
Page 62
PowerScript Topics
Although you can use global system functions or expressions to initialize variables with
compile time values in a variable declaration statement, for runtime value assignments, you
must also declare variables and assign their values in separate statements.
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 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 February 1, 2004:
date ld_StartDate = 2004-02-01
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 at runtime.
If the expression's value changes
Because the expression's value is set to the variable when the script is compiled (not at
runtime) 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.
In this declaration, the value of d_date is the date the script is compiled:
date d_date = Today( )
In contrast, these statements result in d_date being set to the date the application is run:
date d_date
Page 63
PowerScript Topics
d_date = Today( )
Page 64
PowerScript Topics
Syntax
{ access-right } { readaccess } { writeaccess } datatype variablename
The following table describes the parameters you can use to specify access rights for instance
variables.
Table 1.14: Instance variable declaration parameters for access rights
Parameter Description
access-right A keyword specifying where the variable's name will be recognized. Values
(optional) are:
• PUBLIC -- (Default) Any script in the application can refer to the variable.
In another object's script, you use dot notation to qualify the variable name
and identify the object it belongs to.
• PROTECTED -- Scripts for the object for which the variable is declared
and its descendants can refer to the variable.
• PRIVATE -- Scripts for the object for which the variable is declared can
refer to the variable. You cannot refer to the variable in descendants of the
object.
readaccess A keyword restricting the ability of scripts to read the variable's value. Values
(optional) are:
• PROTECTEDREAD -- Only scripts for the object and its descendants can
read the variable.
• PRIVATEREAD -- Only scripts for the object can read the variable.
When access-right is PUBLIC, you can specify either keyword. When access-
right is PROTECTED, you can specify only PRIVATEREAD. You cannot
specify a modifier for PRIVATE access, because PRIVATE is already fully
restricted.
If readaccess is omitted, any script can read the variable.
writeaccess A keyword restricting the ability of scripts to change the variable's value.
(optional) 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 datatype. See Syntax of a variable declaration.
Page 65
PowerScript Topics
Parameter Description
variablename A valid identifier. See Syntax of a variable declaration.
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).
When you look at exported object syntax, you might 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:
protected privatewrite string is_label
These declarations have public access (the default) but can only be changed by scripts in the
object itself:
privatewrite real ir_accum, ir_current_data
This declaration defines an integer that only the owner objects can write or read but whose
name is reserved at the public level:
public privateread privatewrite integer ii_reserved
In a script you declare an instance of the window called w_myemp. If you refer to the private
variable ii_int, you get a compiler warning that the variable is not defined (because the
variable is private and is not recognized in scripts outside the window itself):
w_emp w_myemp
w_myemp.ii_int = 1 // Variable not defined
Page 66
PowerScript Topics
Suppose you have defined a window w_emp with a public integer variable ii_int with write
access restricted to private:
public privatewrite integer ii_int
If you write the same script as above, the compiler warning will say that you cannot write to
the variable (the name is recognized because it is public, but write access is not allowed):
w_emp w_myemp
w_myemp.ii_int = 1 // Cannot write to variable
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
Page 67
PowerScript Topics
Syntax
CONSTANT { access } datatype constname = value
Usage
When declaring a constant, an initial value is required. Otherwise, a compiler error occurs.
Assigning a value to a constant after it is declared (that is, redefining a constant in a
descendant object) also causes a compiler error.
Examples
Although PowerScript is not case sensitive, these examples of local constants use a
convention of capitalizing constant names:
constant string LS_HOMECITY = "Boston"
constant real LR_PI = 3.14159265
Page 68
PowerScript Topics
The following table describes the parameters used to declare array variables.
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).
You can define additional arrays with the same datatype by naming additional
variable names with brackets and optional value lists, separated by commas.
[ { d1, ..., Brackets and (for fixed-size arrays) one or more integer values (d1 through dn,
dn } ] one for each dimension) specifying the sizes of the dimensions.
For a variable-size array, which is always one-dimensional, specify brackets
only.
For more information on how variable-size arrays change size, see Size of
variable-size arrays.
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 values are separated by
(optional) 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 datatype of the values must
match datatype.
Examples
These declarations create variable-size arrays:
integer li_stats[ ] // Array of integers.
decimal {2} ld_prices[ ] // Array of decimals with
// 2 places of precision.
blob lb_data[ ] // Array of variable-size
Page 69
PowerScript Topics
// blobs.
date ld_birthdays[ ] // Array of dates.
string ls_city[ ] // Array of strings.
// Each string can be
// any length.
This statement declares a variable-size array of decimal number (the declaration does not
specify a precision, so each element in the array takes the precision of the value assigned to
it):
dec lc_limit[ ]
Fixed arrays
These declarations create fixed-size, one-dimensional arrays:
integer li_TaxCode[3] // Array of 3 integers.
string ls_day[7] // Array of 7 strings.
blob ib_image[10] // Array of 10
// variable-size blobs.
dec{2} lc_Cost[10] // Array of 10 decimal
// numbers.
// Each value has 2 digits
// following the decimal
// point.
decimal lc_price[20] // Array of 20 decimal
// numbers.
// Each takes the precision
// of the value assigned.
This declaration specifies that the indexes for the dimensions are 1 to 5 and 10 to 25:
integer li_RunRate[1 to 5, 10 to 25]
Page 70
PowerScript Topics
This declaration changes the subscript range for the second and third dimension:
integer li_staff[100, 0 to 20, -5 to 5]
the elements li_TaxCode[1], li_TaxCode[2], and li_TaxCode[3] are all initialized to zero.
For information about default values for basic datatypes, see Initial values for variables.
Simple array
In a simple array, you can override the default values by initializing the elements of the
array when you declare the array. You specify the values in a comma-separated list of values
enclosed in braces. You do not have to initialize all the elements of the array, but you cannot
initialize values in the middle or end without initializing the first elements.
Multidimensional array
In a multidimensional array, you still provide the values in a simple, comma-separated list.
When the values are assigned to array positions, the first dimension is the fastest-varying
dimension, and the last dimension is the slowest-varying. In other words, the values are
assigned to array positions by looping over all the values of the first dimension for each value
of the second dimension, then looping over all the values of the second dimension for each
value of the third, and so on.
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}
Examples
Example 1
This statement declares an initialized one-dimensional array of three variables:
Page 71
PowerScript Topics
Example 2
This statement initializes a two-dimensional array:
integer li_units[3,4] = {1,2,3, 1,2,3, 1,2,3, 1,2,3}
As a result:
Li_units[1,1], [1,2], [1,3], and [1,4] are all 1
Li_units[2,1], [2,2], [2,3], and [2,4] are all 2
Li_units[3,1], [3,2], [3,3], and [3,4] are all 3
Example 3
This statement initializes the first half of a 3-dimensional array:
integer li_units[3,4,2] = &
{1,2,3, 1,2,3, 1,2,3, 1,2,3}
As a result:
Li_units[1,1,1], [1,2,1], [1,3,1], and [1,4,1] are all 1
Li_units[2,1,1], [2,2,1], [2,3,1], and [2,4,1] are all 2
Li_units[3,1,1], [3,2,1], [3,3,1], and [3,4,1] are all 3
Li_units[1,1,2], [1,2,2], [1,3,2], and [1,4,2] are all 0
Li_units[2,1,2], [2,2,2], [2,3,2], and [2,4,2] are all 0
Li_units[3,1,2], [3,2,2], [3,3,2], and [3,4,2] are all 0
For example, these statements declare a variable-size array and assigns values to three array
elements:
long ll_price[ ]
ll_price[100] = 2000
Page 72
PowerScript Topics
ll_price[50] = 3000
ll_price[110] = 5000
• 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].
To a bounded array
If the source array is smaller, values from the source array are copied to the target array and
extra values are set to zero. In this example, b[5] and b[6] are set to 0:
integer a[ ], b[6]
a = {1,2,3,4}
b = a
If the source array is larger, values from the source array are copied to the target array until
it is full (and extra values from the source array are ignored). In this example, the array b has
only the first three elements of a:
integer a[ ], b[3]
a = {1,2,3,4}
b = a
Page 73
PowerScript Topics
Multidimensional arrays
PowerBuilder stores multidimensional arrays in column major order, meaning the first
subscript is the fastest varying -- [1,1], [2,1], [3,1]).
When you assign one array to another, PowerBuilder linearizes the source array in column
major order, making it a one-dimensional array. PowerBuilder then uses the rules for one-
dimensional arrays (described above) to assign the array to the target.
Not all array assignments are allowed, as described in the following rules.
One multidimensional array to another
If the dimensions of the two arrays match, the target array becomes an exact copy of the
source:
integer a[2,10], b[2,10]
a = b
If both source and target are multidimensional but do not have matching dimensions, the
assignment is not allowed and the compiler reports an error:
integer a[2,10], b[4,10]
a = b // Compiler error
Examples
Suppose you declare three arrays (a, b, and c). One (c) is unbounded and one-dimensional;
the other two (a and b) are multidimensional with different dimensions:
integer c[ ], a[2,2], b[3,3] = {1,2,3,4,5,6,7,8,9}
Table 1.17:
1 for b[1,1] 4 for b[1,2] 7 for b[1,3]
2 for b[2,1] 5 for b[2,2] 8 for b[2,3]
3 for b[3,1] 6 for b[3,2] 9 for b[3,3]
This statement causes a compiler error, because a and b have different dimensions:
a = b // Compiler error
Page 74
PowerScript Topics
c = b
Table 1.18:
1 for a[1,1] 3 for a[1,2]
2 for a[2,1] 4 for a[2,2]
In this declaration, a fixed-size array is initialized with four values (the rest of its values are
zeros):
integer a[10] = {1,2,3,4}
In this declaration, a fixed-size array is initialized with four values. Because the array's size is
set at 4, the rest of the values in the arraylist are ignored:
integer a[4] = {1,2,3,4,5,6,7,8}
In this declaration, values 1, 2, and 3 are assigned to the first column and the rest to the
second column:
integer a[3,2] = {1,2,3,4,5,6}
Table 1.19:
1 4
2 5
3 6
If you think of a three-dimensional array as having pages of rows and columns, then the first
column of the first page has the values 1 and 2, the second column on the first page has 3 and
4, and the first column on the second page has 5 and 6.
The second column on the second page has zeros:
integer a[2,2,2] = {1,2,3,4,5,6}
Page 75
PowerScript Topics
Table 1.20:
1 3 5 0
2 4 6 0
Variable-size arrays
Assigning a value to an element of a variable-size array that is outside its current values
increases the array's size. However, accessing a variable-size array above its largest assigned
value or below its lower bound causes an error at runtime:
integer li_stock[ ]
li_stock[50]=200
// Establish array size 50 elements.
IF li_stock[51]=0 then Beep(1)
// This causes an execution error.
IF li_stock[0]=0 then Beep(1)
// This causes an execution error.
To understand how to declare and call an external function, see the documentation from the
developer of the external function library.
Page 76
PowerScript Topics
Syntax
External function syntax
Use the following syntax to declare an external function:
{ access } FUNCTION returndatatype name ( { { REF } datatype1 arg1,
..., { REF } datatypen argn } ) LIBRARY "libname"
ALIAS FOR "extname{;ansi}"
The following table describes the parameters used to declare external functions and
subroutines:
Page 77
PowerScript Topics
Parameter Description
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.
;ansi Required if the function passes a string as an argument or returns a string
that uses ANSI encoding. Even if you use the default name for an ANSI
function, you must always use the ALIAS keyword if you want to specify
that the string uses ANSI encoding, because you must qualify the ALIAS
with the ansi keyword.
Usage
Specifying access of local functions
When declaring a local external function, you can specify its access level -- which scripts
have access to the function.
The following table describes where local external functions can be used when they are
declared with a given access level:
Use of the access keyword with local external functions works the same as the access-right
keywords for instance variables.
Availability of the dynamic library at runtime
To be available to a PowerBuilder application running on any Windows platform, the DLL
must be in one of the following directories:
Examples
In the examples application that comes with PowerBuilder, external functions are declared as
local external functions in a user object called u_external_function_win32. The scripts that
call the functions are user object functions, but because they are part of the same user object,
you do not need to use object notation to call them.
Example 1
Page 78
PowerScript Topics
These declarations allow PowerBuilder to call the functions required for playing a sound in
the WINMM.DLL:
//playsoundFUNCTION boolean sndPlaySoundA (string SoundName,
uint Flags) LIBRARY "WINMM.DLL" ALIAS FOR "sndPlaySoundA;ansi"
FUNCTION uint waveOutGetNumDevs () LIBRARY "WINMM.DLL"
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 Windows 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 Windows documentation:
RETURN GetSysColor (ai_index)
Example 3
This is the declaration for the Windows GetSystemMetrics 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)
Page 79
PowerScript Topics
Windows 32-bit FAR pointers, such as LPBYTE, LPDWORD, LPINT, LPLONG, LPVOID,
and LPWORD, are declared in PowerBuilder as long datatypes. HANDLE is defined as 32
bits unsigned and is declared in PowerBuilder as an UnsignedLong.
Near-pointer datatypes (such as PSTR and NPSTR) are not supported in PowerBuilder.
Characters and strings
Table 1.24: PowerBuilder datatypes for characters and strings
Datatype in source code Size, sign, precision PowerBuilder datatype
char 8 bits, signed Char
string 32-bit pointer to a null- String
terminated array of bytes of
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.
Fixed-point values
Page 80
PowerScript Topics
Page 81
PowerScript Topics
32-bit applications. This was an intentional change. Customers can now call Windows API
easier and use the same code for both 64-bit and 32-bit applications.
Customers can switch to the old behavior in two ways with PowerBuilder 12.6 build 4058
and above.
1. Check "Use 1-byte structure member alignment in external function" (or set UseZp1=1
in [pb] section, pb.ini, the results are the same). The effect is global with this setting
changed. To make this work at runtime, please remember to deploy your pb.ini file with your
application.
2. Add “progma_pack(1)” external function’s declaration, like this:
FUNCTION int STLAREGIO ( ref struc_kfzrechnerneu struc_kfz ) LIBRARY
"KFZ_SS.DLL" alias for "STLAREGIO;Ansi" progma_pack(1)
progma_pack(1) is 1-byte align, progma_pack(8) is 8-bytes align. In this way, the effect is
only for external function that is declared with this alignment.
Page 82
PowerScript Topics
You can call database procedures in SAP, Oracle, Informix, and other ODBC databases with
stored procedures.
RPCs provide support for Oracle PL/SQL tables and parameters that are defined as both input
and output. You can call overloaded procedures.
Applies to
Transaction object
Syntax
FUNCTION rtndatatype functionname ( { { REF } datatype1 arg1,...,
{ REF } datatypen argn } ) RPCFUNC { ALIAS FOR "spname" }
SUBROUTINE functionname ( { { REF } datatype1 arg1 , ...,
{ REF } datatypen argn } ) RPCFUNC { ALIAS FOR "spname" }
Page 83
PowerScript Topics
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.
ALIAS FOR Keywords followed by a string naming the procedure in the database. If
"spname" (optional)
the name in the database 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 "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 box 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 Section 4.1.3, “Using Transaction objects to call stored
procedures” in 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"
Example 2
This declaration for the stored procedure SPM8 does not need an ALIAS FOR phrase,
because the PowerBuilder and DBMS names are the same:
FUNCTION integer SPM8(integer value) RPCFUNC
Page 84
PowerScript Topics
This chapter describes the operators supported in PowerScript and how to use them in
expressions.
Usage
Operator shortcuts for assignments
For information about shortcuts that combine arithmetic operators with assignments (such as
++ and +=), see Assignment.
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.
Page 85
PowerScript Topics
• Overflow of signed or unsigned integers and longs causes results to wrap. However,
because integers are promoted to longs in calculations, wrapping does not occur until the
result is explicitly assigned to an integer variable.
For more information about type promotion, see Datatype of PowerBuilder expressions.
Examples
Subtraction
This statement always means subtract B from A:
A - B
If DashesInIdentifiers is set to 1, the following statement means a variable named A-B, but if
DashesInIdentifiers is set to 0, it means subtract B from A:
A-B
SetNULL(c)
Page 86
PowerScript Topics
Overflow
This example illustrates the value of the variable i after overflow occurs:
integer i
i = 32767
i = i + 1 // i is now -32768
Usage
Comparing strings
When PowerBuilder compares strings, the comparison is case sensitive. Trailing blanks are
significant.
For information on comparing strings regardless of case, see the functions Upper and Lower.
To remove trailing blanks, use the RightTrim function. To remove leading blanks, use
the LeftTrim function. To remove leading and trailing blanks, use the Trim function. For
information about these functions, see RightTrim, LeftTrim, and Trim.
Decimal operands
Page 87
PowerScript Topics
Relational operators that operate on numeric values (including =, >, <, <>, >=, and <=) can
take decimal operands. The precision of the decimal operand is maintained in comparisons.
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.
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 ... // Returns FALSE
City1 = "Austin"
City2 = "AUSTIN"
IF Upper(City1) = Upper(City2)... // Returns TRUE
Examples
Example 1
Page 88
PowerScript Topics
Example 2
This example shows how a blob can act as an accumulator when reading data from a file:
integer i, fnum, loops
blob tot_b, b
. . .
FOR i = 1 to loops
bytes_read = FileRead(fnum, b)
tot_b = tot_b + b
NEXT
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.
Page 89
PowerScript Topics
• +, -, *
Page 90
PowerScript Topics
The minimum precision for addition, subtraction, and multiplication calculations is long.
Integer types are promoted to long types before doing the calculation and the expression's
resulting datatype is, at a minimum, long. When operands have datatypes of higher
precedence, other operands are promoted to match based on the Datatypes of operands rule
above.
• / and ^
The minimum precision for division and exponentiation is double. All types are promoted
to double before doing the calculation, and the expression's resulting datatype is double.
• Relational
Relational operators do not cause promotion of numeric types.
Datatypes of literals
When a literal is an operand in an expression, its datatype is determined by the literal's value.
The datatype of a literal affects the type promotion of the literal and other operands in an
expression.
Out of range
Integer literals beyond the range of LongLong cause compiler errors.
the datatype of a+b is determined by the datatypes of a and b. Then, the result is converted to
the datatype of c.
Page 91
PowerScript Topics
Overflow on assignment
Even when PowerBuilder performs a calculation at high enough precision to handle the
results, assignment to a lower precision variable can cause overflow, producing the wrong
result.
Example 1
Consider this code:
integer a = 32000, b = 1000
long d
d = a + b
The resulting value of c and e is -32536. The calculation proceeds like this:
Add the integers a and b
Assign the result to c
Convert integer c to long and assign the result to e
The assignment to the integer variable c causes the long result of the addition to be truncated,
causing overflow and wrapping. Assigning c to e cannot restore the lost information.
• When a string literal is assigned to a char variable, the first character of the string literal is
assigned to the variable. For example:
char c = "xyz"
• Special characters (such as newline, formfeed, octal, hex, and so on) can be assigned to
char variables using string conversion, such as:
Page 92
PowerScript Topics
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.
• 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.
Page 93
PowerScript Topics
When you define a structure in the 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 Section 3.4, “Working with Structures” in Users
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
str_emp2.emp_id = 101
str_emp2.emp_salary = str_emp1.salary * 1.05
The following 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
The following statement in a script for some other object qualifies the structure with the
window name:
w_customer.str_cust1.name
Page 94
PowerScript Topics
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 user objects
There are two categories of objects supported by PowerBuilder: system 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 the base class PowerObject.
The system classes are the ancestors of all the objects you define. To see the system class
hierarchy, select the System tab in the Browser, select PowerObject, and select Show
Hierarchy and Expand All from the pop-up menu.
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, the 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.
Page 95
PowerScript Topics
For information on defining and using user objects, see the Section 4.7, “Working with User
Objects” in Users Guide.
Page 96
PowerScript Topics
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.
Page 97
PowerScript Topics
• 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.
Page 98
PowerScript Topics
• When you assign one structure to another, the whole structure is copied so that there are
two copies of the structure.
• When you assign one object variable to another, the object reference is copied so that both
variables point to the same object. There is only one copy of the object.
Events
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:
Page 99
PowerScript Topics
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.
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
Create an instance of the descendant and store the reference in the ancestor variable:
uo_emp1 = CREATE USING "uo_emp_active"
Assigning uo_emp1 to uo_emp2 makes both variables refer to one object that is an instance
of the descendant uo_emp_active:
uo_emp2 = uo_emp1
For information about passing objects as function arguments, see Passing arguments to
functions and events.
When you assign an autoinstantiated object to another autoinstantiated object, the whole
object is copied to the second variable:
uo_emp1 = uo_emp2
Page 100
PowerScript Topics
When you pass an autoinstantiated user object to a function, it behaves like a structure:
• Passing by reference passes a pointer to the object variable, just as for any standard
datatype.
• Passing as read-only passes a copy of the object but that copy cannot be modified.
Example of rule 1
When assigning one instance to another from the user objects declared above, some
assignments are not allowed by the compiler:
uo_empb = uo_empa // Allowed, same type
uo_empa = uo_empi // Not allowed, different types
Example of rule 2
After this assignment, uo_emp1 contains a copy of the descendant object uo_empa.
Uo_emp_data (the type for uo_emp1) must not be autoinstantiated. Otherwise, the
assignment violates rule 1. If uo_emp1 is autoinstantiated, a compiler error occurs:
uo_emp1 = uo_empa
Example of rule 3
This assignment is only allowed if uo_emp1 contains an instance of its descendant uo_empa,
which it would if the previous assignment had occurred before this one:
uo_empa = uo_emp1
Page 101
PowerScript Topics
If it did not contain an instance of target descendant type, an execution error would occur.
For more information about passing arguments to functions and events, see Passing
arguments to functions and events.
Page 102
PowerScript Topics
Category
Item Definition
User-defined A function you define. You define global functions in the Function
function painter and object functions in other painters with Script views.
Global A function you define that can be called from any script.
function PowerScript's system functions are globally accessible, but they
have a different place in the search order.
Local external An external function that belongs to an object. You declare it in the
function Window or User Object painter. Its definition is in another library.
Global An external function that you declare in any painter, making it
external globally accessible. Its definition is in another library.
function
Remote A stored procedure in a database that you can call from a script.
procedure call The declaration for an RPC can be global or local (belonging to an
(RPC) object). The definition for the procedure is in the database.
• You can call object functions and events dynamically or statically. Global or system
functions cannot be called dynamically.
• Functions can be global or part of an object's definition. Events are associated only with
objects.
• PowerBuilder uses different search orders when looking for events and functions.
• A call to an undefined function triggers an error. A call to an undefined event does not
trigger an error.
• When you define a function, you can restrict access to it. You cannot add scope restrictions
when you define events.
• When functions are inherited, you can extend the ancestor function by calling it in the
descendant's script. You can also override the function definition. When events are
inherited, the scripts for those events are extended by default. You can choose to extend or
override the script.
Which to use
Page 103
PowerScript Topics
Whether you write most of your code in user-defined functions or in event scripts is one of
the design decisions you must make. Because there is no performance difference, the decision
is 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 might want to choose one approach for handling most situations.
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.
Page 104
PowerScript Topics
dw_1.Update( )
w_employee.uf_process_list()
This.uf_process_list()
When PowerBuilder searches the ancestor hierarchy for a function, you can specify that you
want to call an ancestor function instead of a matching descendant function.
For the syntax for calling ancestor functions, see Calling functions and events in an object's
ancestor.
Page 105
PowerScript Topics
Posting
When you post a function or event, it is added to the object's queue and executed in its turn.
In most cases, it is executed when the current script is finished; however, if other system
events have occurred in the meantime, its position in the queue might be after other scripts.
Its return value is not available to the calling script.
Because POST makes the return value unavailable to the caller, you can think of it as turning
the function or event call into a statement.
Use posting when activities need to be finished before the code checks state information or
does further processing (see Example 2 below).
PowerBuilder messages processed first
All events posted by PowerBuilder are processed by a separate queue from the Windows
system queue. PowerBuilder posted messages are processed before Windows posted
messages, so PowerBuilder events that are posted in an event that posts a Windows message
are processed before the Windows message.
For example, when a character is typed into an EditMask control, the PowerBuilder
pdm_keydown event posts the Windows message WM_CHAR to enter the character. If you
want to copy the characters as they are entered from the EditMask control to another control,
do not place the code in an event posted in the pdm_keydown event. The processing must
take place in an event that occurs after the WM_CHAR message is processed, such as in an
event mapped to pdm_keyup.
Restrictions for POST
Because no value is returned, you:
• Cannot use a posted function or event as the argument for another function
• Can only use POST on the last call in a cascaded sequence of calls
These statements cause a compiler error. Both uses require a return value:
IF POST IsNull( ) THEN ...
w_1.uf_getresult(dw_1.POST GetBorderStyle(2))
Examples of posting
The following examples illustrate how to post events.
Example 1
In a sample application, the Open event of the w_activity_manager window calls the
functions uf_setup and uf_set_tabpgsystem. (The functions belong to the user object
Page 106
PowerScript Topics
u_app_actman.) Because the functions are posted, the Open event is allowed to finish before
the functions are called. The result is that the window is visible while setup processing takes
place, giving the user something to look at:
guo_global_vars.iuo_app_actman.POST uf_setup()
guo_global_vars.iuo_com_actman.POST uf_set_tabpgsystem(0)
Example 2
In a sample application, the DoubleClicked event of the tv_roadmap TreeView control in the
u_tabpg_amroadmap user object posts a function that processes the TreeView item. If the
event is not posted, the code that checks whether to change the item's picture runs before the
item's expanded flag is set:
parent.POST uf_process_item ()
Page 107
PowerScript Topics
When you specify a dynamic call in PowerBuilder, the function or event does not have to
exist when you compile the code. You are indicating to the compiler that 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 do not exist in the ancestor.
Results of dynamic calls
To illustrate the results of dynamic calls, consider these objects:
• Descendant window w_a_desc with two functions: Set(integer) overrides the ancestor
function, and Set(string) is an 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:
Table 1.37:
This statement Has this result
mywindow.Set(1) Compiles correctly because function is found
in the ancestor w_a.
At runtime, Set(integer) in the ancestor is
executed.
mywindow.Set("hello") Fails to compile; no function prototype in
w_a matches the call.
mywindow.DYNAMIC Set("hello") Compiles successfully because of the
DYNAMIC keyword.
An error occurs at runtime because no
matching function is found.
Situation 2
Page 108
PowerScript Topics
Now suppose you open mywindow as the descendant window class w_a_desc:
w_a mywindow
Open(mywindow, "w_a_desc")
This is what happens when you call the Set function statically or dynamically in the
descendant window class:
Table 1.38:
This statement Has this result
mywindow.Set(1) Compiles correctly because function is found
in the ancestor w_a.
At runtime, Set(integer) in the descendant is
executed.
mywindow.Set("hello") Fails to compile; no function prototype in the
ancestor matches the call.
mywindow.DYNAMIC Set("hello") Compiles successfully because of the
DYNAMIC keyword.
At runtime, Set(string) in the descendant is
executed.
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 runs, the value of variable ish_currentsheet is
a descendant window that does have a definition for wf_export:
Page 109
PowerScript Topics
guo_global_vars.ish_currentsheet.DYNAMIC wf_export()
Events
Consider these statements:
Page 110
PowerScript Topics
Page 111
PowerScript Topics
If you call an event dynamically and the arguments do not 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. When
that is not possible, your design and testing can ensure that there is always an appropriate
function or event with the correct return datatype.
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 datatype 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
Page 112
PowerScript Topics
version of the function. Overloading with unrelated datatypes is a good idea and can provide
needed functionality for your application.
Problematic overloading
If different versions of a function have arguments of related datatypes (different numeric
types or strings and chars), you must consider how PowerBuilder promotes datatypes in
determining which function is called. This kind of overloading is undesirable because of
potential confusion in determining which function is called.
When you call a function with an expression as an argument, the datatype of the expression
might not be obvious. However, the datatype is important in determining what version of an
overloaded function is called.
Because of the intricacies of type promotion for numeric datatypes, you might decide that
you should not define overloaded functions with different numeric datatypes. 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 datatypes of constants and
variables so that it can process or combine them correctly.
Numbers
When PowerBuilder evaluates numeric expressions, it promotes the datatypes of values
according to the operators and the datatypes of the other operands. For example, the datatype
of the expression n/2 is double because it involves division -- the datatype of n does not
matter.
Strings
When evaluating an expression that involves chars and strings, PowerBuilder promotes chars
to strings.
For more information on type promotion, see Datatype of PowerBuilder expressions.
Using conversion functions
You can take control over the datatypes of expressions by calling a conversion function.
The conversion function ensures that the datatype of the expression matches the function
prototype you want to call.
For example, because the expression n/2 involves division, the datatype 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))
Page 113
PowerScript Topics
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 extending or overriding, open the script in the Script view and check or clear the
Extend Ancestor Script item in the Edit or pop-up menu.
Page 114
PowerScript Topics
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)
Page 115
PowerScript Topics
1.6.7.1 Functions
All built-in PowerScript functions return a value. You can use the return value or ignore it.
User-defined functions and external functions might or might not return a value.
To use a return value, assign it to a variable of the appropriate datatype or call the function
wherever you can use a value of that datatype.
Posting a function
If you post a function, you cannot use its return value.
Examples
The built-in Asc function takes a string as an argument and returns the Unicode code point
value of the string's first character:
string S1 = "Carton"
long Test
Test=32+Asc(S1) // Test now contains the value 99
// (the code point 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)
1.6.7.2 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.
Page 116
PowerScript Topics
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.
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
Page 117
PowerScript Topics
The following table describes the arguments used in function and event calls.
Table 1.42: Arguments for calling functions and events
Argument Description
objectname The name of the object where the function or event is defined followed by a
(optional) period or the descendant of that object/the name of the ancestor class followed
by two colons.
If a function name is not qualified, PowerBuilder uses the rules for finding
functions and executes the first matching function it finds.
For system or global functions, omit objectname.
For the rules PowerBuilder uses to find unqualified function names, see
Finding and executing functions and events.
type A keyword specifying whether you are calling a function or event. Values are:
(optional)
• FUNCTION (Default)
• EVENT
calltype A keyword specifying when PowerBuilder looks for the function or event.
(optional) Values are:
• STATIC (Default)
• DYNAMIC
For more information about static versus dynamic calls, see Static versus
dynamic calls. For more information on dynamic calls, see Dynamic calls.
when A keyword specifying whether the function or event should execute
(optional) immediately or after the current script is finished. Values are:
• POST -- Put it in the object's queue and execute it in its turn, after other
pending messages have been handled.
For more about triggering and posting, see Triggering versus posting functions
and events.
name The name of the function or event you want to call.
argumentlist The values you want to pass to name. Each value in the list must have a
(optional) datatype that corresponds to the declared datatype in the function or event
definition or declaration.
Usage
Function and event names are not case sensitive. For example, the following three statements
are equivalent:
Clipboard("PowerBuilder")
Page 118
PowerScript Topics
clipboard("PowerBuilder")
CLIPBOARD("PowerBuilder")
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 is 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, use the ancestor operator (::).
For more information about the scope operator for ancestors, see Calling functions and events
in an object's ancestor.
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.
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.
External functions
Before you can call an external function, you must declare it. For information about declaring
external functions, see Declaring external functions.
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( )
Page 119
PowerScript Topics
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)
Example 5
The variable iw_a is an instance variable of an ancestor window type w_ancestorsheet:
w_ancestorsheet iw_a
A menu has a script that calls the wf_export function, but that function is not defined in the
ancestor. The DYNAMIC keyword is required so that the script compiles:
iw_a.DYNAMIC wf_export( )
At execution time, the window that is opened is a descendant with a definition of wf_export.
That window is assigned to the variable iw_a and the call to wf_export succeeds.
Page 120
PowerScript Topics
ancestor's version of a function or event, you can use the ancestor operator (::) to call the
ancestor's version explicitly.
Syntax
{ objectname. } ancestorclass ::{ type } { when } name ( { argumentlist } )
The following table describes the arguments used to call functions and events in an object's
ancestor.
Table 1.43: Arguments for calling ancestor functions and events
Argument Description
objectname The name of the object whose ancestor contains the function you want to
(optional) execute.
ancestorclass The name of the ancestor class whose function or event you want to execute.
The pronoun Super provides the appropriate reference when ancestorobject is
the immediate ancestor of the current object.
type A keyword specifying whether you are calling a function or event. Values are:
(optional)
• (Default) FUNCTION
• EVENT
when A keyword specifying whether the function or event should execute
(optional) immediately or after the current script is finished. Values are:
• POST -- Put it in the object's queue and execute it in its turn, after other
pending messages have been handled
name The name of the object function or event you want to call.
argumentlist The values you want to pass to name. Each value in the list must have a
(optional) datatype that corresponds to the declared datatype in the function definition.
Usage
The AncestorReturnValue variable
When you extend an event script in a descendant object, the compiler automatically generates
a local variable called AncestorReturnValue that you can use if you need to know the return
value of the ancestor event script. The variable is also generated if you override the ancestor
script and use the CALL syntax to call the ancestor event script.
The datatype of the AncestorReturnValue variable is always the same as the datatype defined
for the return value of the event. The arguments passed to the call come from the arguments
that are passed to the event in the descendant object.
Extending event scripts
The AncestorReturnValue variable is always available in extended event scripts. When you
extend an event script, PowerBuilder generates the following syntax and inserts it at the
beginning of the event script:
CALL SUPER::event_name
Page 121
PowerScript Topics
You only see the statement if you export the syntax of the object or look at it in the Source
editor.
The following example illustrates the code you can put in an extended event script:
If AncestorReturnValue = 1 THEN
// execute some code
ELSE
// execute some other code
END IF
The compiler cannot differentiate between the keyword SUPER and the name of the ancestor.
The keyword is replaced with the name of the ancestor before the script is compiled.
The AncestorReturnValue variable is only declared and a value assigned when you use the
CALL event syntax. It is not declared if you use the new event syntax:
ancestor_name::EVENT event_name( )
You can use the same code in a script that overrides its ancestor event script, but you must
insert a CALL statement before you use the AncestorReturnValue variable.
// execute code that does some preliminary processing
CALL SUPER::uo_myevent
IF AncestorReturnValue = 1 THEN
...
This statement calls the ancestor event only (this script works if the calling script belongs to
another object or the descendant window):
w_ancestor::EVENT ue_process( )
Example 2
You can use the pronoun Super to refer to the ancestor. This statement in a descendant
window script or in a script for a control on that window calls the Clicked script in the
immediate ancestor of that window.
Page 122
PowerScript Topics
Super::EVENT Clicked(0, x, y)
Example 3
These statements call a function wf_myfunc in the ancestor window (presumably, the
descendant also has a function called wf_myfunc):
Super::wf_myfunc( )
Super::POST wf_myfunc( )
Page 123
Statements, Events, and Functions
2.1.1 Assignment
Description
Assigns values to variables or object properties or object references to object variables.
Syntax
variablename = expression
Table 2.1:
Argument Description
variablenameThe 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 datatype is compatible with variablename.
Usage
Use assignment statements to assign values to variables. To assign a value to a variable
anywhere in a script, use the equal sign (=). For example:
String1 = "Part is out of stock"
TaxRate = .05
No multiple assignments
Since the equal sign is also a logical operator, you cannot assign more than one variable in a
single statement. For example, the following statement does not assign the value 0 to A and
B:
A=B=0 // This will not assign 0 to A and B.
This statement first evaluates B=0 to true or FALSE and then tries to assign this boolean
value to A. When A is not a boolean variable, this line produces an error when compiled.
Assigning array values
You can assign multiple array values with one statement, such as:
int Arr[]
Arr = {1, 2, 3, 4}
You can also copy array contents. For example, this statement copies the contents of Arr2
into array Arr1:
Arr1 = Arr2
Page 124
Statements, Events, and Functions
Operator shortcuts
The PowerScript shortcuts for assigning values to variables in the following table ave slight
performance advantages over their equivalents.
Table 2.2: Shortcuts for assigning values
Assignment Example Equivalent to
++ i ++ i=i+1
-- i -- i=i-1
+= i += 3 i=i+3
-= i -= 3 i = i -3
*= i *= 3 i=i*3
/= i /= 3 i=i/3
^= i ^=3 i=i^3
Unless you have prohibited the use of dashes in variable names, you must leave a space
before -- and -=. If you do not, PowerScript reads the minus sign as part of a variable name.
For more information, see Identifier names.
Examples
Example 1
These statements each assign a value to the variable ld_date:
date ld_date
ld_date = Today( )
ld_date = 2006-01-01
ld_date = Date("January 1, 2006")
Example 2
These statements assign 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 assign the value to the string Text1:
string Text1
Text1 = sle_emp.Text+".DAT"
Example 6
Page 125
Statements, Events, and Functions
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
2.1.2 CALL
Description
Calls an ancestor script from a script for a descendant 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.
Syntax
CALL ancestorobject {`controlname}::event
Table 2.3:
Parameter Description
ancestorobject An ancestor of the descendant object
controlname (optional) The name of a control in an ancestor window
or custom user object
event An event in the ancestor object
Usage
Page 126
Statements, Events, and Functions
In some circumstances, you can use the pronoun Super when ancestorobject is the descendant
object's immediate ancestor. See the discussion of Super pronoun.
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
Table 2.4:
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
Page 127
Statements, Events, and Functions
Parameter Description
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.
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
2.1.4 CONTINUE
Description
In a DO...LOOP or a FOR...NEXT control structure, skips statements in the loop.
CONTINUE takes no parameters.
Page 128
Statements, Events, and Functions
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.
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.
2.1.5 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 that 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
Page 129
Statements, Events, and Functions
Table 2.5:
Parameter Description
objectvariable A global, instance, or local variable whose
datatype is objecttype
objecttype The object datatype
Table 2.6:
Parameter Description
objectvariable A global, instance, or local variable whose
datatype 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
datatype 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.)
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:
• Any object that has been instantiated using a function, such as Open
Page 130
Statements, Events, and Functions
IF ... THEN
ls_objectname = "uo_a_desc1"
ELSE
ls_objectname = "uo_a_desc2"
END IF
uo_a_var = CREATE USING ls_objectname
Example 2
These statements create a user object when the application has need of the services it
provides. Because the user object might or might 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
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 verifies
that invo_service is instantiated:
IF IsValid(invo_service)
THEN
invo_service.of_perform_some_work( )
END IF
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
Page 131
Statements, Events, and Functions
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
lnv_fileservice = CREATE USING ls_objectname
2.1.6 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
Table 2.7:
Parameter Description
objectvariable A variable whose datatype 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 call DESTROY only 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 Garbage collection.
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
Page 132
Statements, Events, and Functions
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 = istg_prod_pic.Open("PICTURES.OLE")
2.1.7 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 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.
Page 133
Statements, Events, and Functions
Table 2.8:
Parameter Description
condition The condition you are testing
statementblock The block of statements you want to repeat
Usage
Use DO WHILE or DO UNTIL when you want to execute a block of statements only if a
condition is true (for WHILE) or false (for UNTIL). DO WHILE and DO UNTIL test the
condition before executing the block of statements.
Use LOOP WHILE or LOOP UNTIL when you want to execute a block of statements at least
once. LOOP WHILE and LOOP UNTIL test the condition after the block of statements has
been executed.
Examples
DO UNTIL
The following DO UNTIL repeatedly executes the Beep function until A is greater than 15:
integer A = 1, B = 1
DO UNTIL A > 15
Beep(A)
A = (A + 1) * B
LOOP
DO WHILE
The following DO WHILE repeatedly executes the Beep function only while A is less than or
equal to 15:
integer A = 1, B = 1
DO WHILE A <= 15
Beep(A)
A = (A + 1) * B
LOOP
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
Page 134
Statements, Events, and Functions
DO
Beep(A)
A = (A + 1) * B
LOOP WHILE A <= 15
2.1.8 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.
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) )
2.1.9 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
Page 135
Statements, Events, and Functions
Table 2.9:
Parameter Description
varname The name of the iteration counter variable. It can be any numerical type (byte,
integer, double, real, long, longlong, 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 the same datatype
(optional) as varname. If you enter an increment, STEP is required. +1 is the default
increment.
statementblockThe block of statements you want to repeat.
Ending statement
You can end the FOR loop with the keywords END FOR instead of NEXT.
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. If the
expression's value changes, it affects 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 or END FOR for each FOR.
Avoid overflow
If start or end is too large for the datatype of varname, varname will overflow, which
might 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.
Page 136
Statements, Events, and Functions
Examples
Example 1
These statements add 10 to A as long as n is >=5 and <=25:
FOR n = 5 to 25
A = A+10
NEXT
Example 2
These statements add 10 to A and increment n by 5 as long as n is >= 5 and <=25:
FOR N = 5 TO 25 STEP 5
A = A+10
NEXT
Example 3
These statements contain two lines that will never execute because increment is negative and
start is less than end:
FOR Count = 1 TO 100 STEP -1
IF Count < 1 THEN EXIT // These 2 lines
Box[Count] = 10 // will never execute.
NEXT
Example 4
These are nested FOR...NEXT statements:
Int Matrix[100,50,200]
FOR i = 1 to 100
FOR j = 1 to 50
FOR k = 1 to 200
Matrix[i,j,k]=1
NEXT
NEXT
NEXT
2.1.10 GOTO
Description
Transfers control from one statement in a script to another statement that is labeled.
Syntax
GOTO label
Table 2.10:
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
Page 137
Statements, Events, and Functions
Example 2
This GOTO statement transfers control to the statement associated with the label OK:
GOTO OK
.
.
.
OK:
.
.
.
2.1.11 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
scripts for application Close event and for the CloseQuery, Close, and Destructor events on
all instantiated objects before terminating the application. If there are no scripts for these
events, PowerBuilder immediately terminates the application.
You should not code a HALT statement in a component that will run in a server environment.
When a PowerBuilder component is running in a J2EE server, and a HALT statement is
encountered, instead of aborting the application, which is in this case the server itself, the
PowerBuilder VM throws a runtime error and continues. The container is responsible for
managing the lifecycle of the component.
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 &
Page 138
Statements, Events, and Functions
2.1.12 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}
Table 2.11:
ParameterDescription
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 false. The action must be a
(optional) single statement on the same line as the rest of the IF statement.
Table 2.12:
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. You can have multiple
(optional) 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 conditions is true.
(optional) The action can be a statement or multiple statements that are separated by
semicolons or placed on separate lines.
Usage
Page 139
Statements, Events, and Functions
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 is equal to 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:
• 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
2.1.13 RETURN
Description
Page 140
Statements, Events, and Functions
Table 2.13:
Parameter Description
expression In a function, any value (or expression) you want the function to return. The
return value must be the datatype 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
2.1.14 THROW
Description
Used to manually trigger exception handling for user-defined exceptions.
Syntax
THROW exlvalue
Table 2.14:
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
Page 141
Statements, Events, and Functions
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 datatype.
For example, you can use an expression such as:
THROW create ExceptionType
ConnectionException ex
ex = create ConnectionException
ex.connectResult = ll_result
THROW ex
end if
2.1.15 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, ... }
Table 2.15:
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.
Usage
Page 142
Statements, Events, and Functions
Table 2.16:
Parameter Description
trystatements Block of code that might potentially throw an exception.
ThrowableTypeN
Object type of exception to be caught. A CATCH block is optional if you
include a FINALLY block. You can include multiple CATCH blocks. Every
CATCH block in a try-catch block must include a corresponding exception
object type and a local variable of that type.
exIdentifierN Local variable of type ThrowableTypeN.
catchstatementsN
Code to handle the exception being caught.
cleanupstatements
Cleanup code. The FINALLY block is optional if you include one or more
CATCH block.
Usage
The TRY block, which is the block of statements between the TRY and CATCH keywords
(or the TRY and FINALLY keywords if there is no CATCH clause), is used to isolate
code that might potentially throw an exception. The statements in the TRY block are run
unconditionally until either the entire block of statements is executed or some statement in
the block causes an exception to be thrown.
Page 143
Statements, Events, and Functions
Use a CATCH block or multiple CATCH blocks to handle exceptions thrown in a TRY
block. In the event that an exception is thrown, execution of the TRY block is stopped and
the statements in the first CATCH block are executed -- if and only if the exception thrown is
of the same type or a descendant of the type of the identifier following the CATCH keyword.
If the exception thrown is not the same type or a descendant type of the identifier in the first
CATCH block, the exception is not handled by this CATCH block. If there are additional
CATCH blocks, they are evaluated in the order they appear. If the exception cannot be
handled by any of the CATCH blocks, the statements in the FINALLY block are executed.
The exception then continues to unwind the call stack to any outer nested try-catch blocks. If
there are no outer nested blocks, the SystemError event on the Application object is fired.
If no exception is thrown, execution continues at the beginning of the FINALLY block if one
exists; otherwise, execution continues on the line following the END TRY statement.
See also
THROW
The same statement using a PowerScript variable to reference the constant might look like
this:
int Sal_var
Sal_var = 18900
INSERT INTO EMPLOYEE ( SALARY ) VALUES ( :Sal_var ) ;
Page 144
Statements, Events, and Functions
Error reporting
Not all DBMSs return a conversion error when the datatype of a column does not
match the datatype 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 can 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 can also use the PowerScript SetNull function to accomplish the same result without
using indicator variables:
SetNull( City )
Page 145
Statements, Events, and Functions
Value Meaning
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
Page 146
Statements, Events, and Functions
Caution
Select the check box only when you want to compile without signing on to the
database. Compiling without connecting to a database prevents the build process from
checking for database errors and may therefore result in runtime errors later.
Table 2.19:
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.
Examples
This statement closes the Emp_cursor cursor:
CLOSE Emp_cursor ;
Page 147
Statements, Events, and Functions
DBMS-specific
Not all DBMSs support stored procedures.
Syntax
CLOSE ProcedureName;
Table 2.20:
Parameter Description
ProcedureName The stored procedure you want to close
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.
Use CLOSE only to close procedures that return result sets. PowerBuilder automatically
closes procedures that do not 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.
Examples
This statement closes the stored procedure named Emp_proc:
CLOSE Emp_proc ;
2.2.1.3 COMMIT
Description
Permanently updates all database operations since the previous COMMIT, ROLLBACK, or
CONNECT for the specified transaction object.
Syntax
COMMIT {USING TransactionObject};
Table 2.21:
Parameter Description
TransactionObject
The name of the transaction object for 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).
Page 148
Statements, Events, and Functions
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 ;
2.2.1.4 CONNECT
Description
Connects to a specified database.
Syntax
CONNECT {USING TransactionObject};
Table 2.22:
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
Page 149
Statements, Events, and Functions
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 ;
Table 2.23:
Parameter Description
CursorName Any valid PowerBuilder name.
SelectStatement Any valid SELECT statement.
TransactionObjectThe 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).
Usage
DECLARE Cursor is a nonexecutable command and is analogous to declaring a variable.
To declare a local cursor, 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,
select Declare from the first drop-down list in the Script view and Global Variables, Instance
Variables, or Shared Variables from the second drop-down list, then select Paste SQL.
For information about global, instance, shared, and local scope, see Where to declare
variables.
Examples
This statement declares the cursor called Emp_cur for the database specified in the default
transaction object. It also references the Sal_var variable, which must be set to an appropriate
value before you execute the OPEN Emp_cur command:
DECLARE Emp_cur CURSOR FOR
SELECT employee.emp_number, employee.emp_name
FROM employee
WHERE employee.emp_salary > :Sal_var ;
Page 150
Statements, Events, and Functions
DBMS-specific
Not all DBMSs support stored procedures.
Syntax
DECLARE ProcedureName PROCEDURE FOR
StoredProcedureName
@Param1=Value1, @Param2=Value2,...
{USING TransactionObject};
Table 2.24:
Parameter Description
ProcedureName Any valid PowerBuilder name.
StoredProcedureName
Any stored procedure in the database.
@Paramn=Valuen
The name of a parameter (argument) defined in the stored procedure and a
valid PowerBuilder expression; represents the number of the parameter and
value.
TransactionObjectThe name of the transaction object for which you want to declare the
procedure. This clause is required only for transaction objects other than
the default (SQLCA).
Usage
DECLARE Procedure is a nonexecutable command. It is analogous to declaring a variable.
To declare a local 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
procedure, select Declare from the first drop-down list in the Script view and Global
Variables, Instance Variables, or Shared Variables from the second drop-down list, then
select Paste SQL.
For information about global, instance, shared, and local scope, see Where to declare
variables.
Examples
Example 1
This statement declares the SAP ASE procedure Emp_proc for the database specified in
the default transaction object. It references the Emp_name_var and Emp_sal_var variables,
which must be set to appropriate values before you execute the EXECUTE Emp_proc
command:
DECLARE Emp_proc procedure for GetName
@emp_name = :Emp_name_var,
@emp_salary = :Emp_sal_var ;
Example 2
This statement declares the ORACLE procedure Emp_proc for the database specified in
the default transaction object. It references the Emp_name_var and Emp_sal_var variables,
which must be set to appropriate values before you execute the EXECUTE Emp_proc
command:
DECLARE Emp_proc procedure for GetName
Page 151
Statements, Events, and Functions
(:Emp_name_var, :Emp_sal_var) ;
2.2.1.7 DELETE
Description
Deletes the rows in TableName specified by Criteria.
Syntax
DELETE FROM TableName WHERE Criteria {USING TransactionObject};
Table 2.25:
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).
Usage
Error handling
It is good practice to test the success/failure code after executing a DELETE
statement. To see if the DELETE was successful, you can test SLQCode for a failure
code. However, if nothing matches the WHERE clause and no rows are deleted,
SQLCode is still set to zero. To make sure the delete affected at least one row, check
the SQLNRows property of the transaction object.
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.
Page 152
Statements, Events, and Functions
DBMS-specific
Not all DBMSs support DELETE Where Current of Cursor.
Syntax
DELETE FROM TableName WHERE CURRENT OF CursorName;
Table 2.26:
Parameter Description
TableName The name of the table from which you want
to delete a row
CursorName The name of the cursor in which the table
was specified
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 ;
2.2.1.9 DISCONNECT
Description
Executes a COMMIT for the specified transaction object and then disconnects from the
specified database.
Syntax
DISCONNECT {USING TransactionObject};
Table 2.27:
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).
Page 153
Statements, Events, and Functions
Usage
Error handling
It is good practice to test the success/failure code after executing a DISCONNECT
statement.
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 ;
2.2.1.10 EXECUTE
Description
Executes the previously declared procedure identified by ProcedureName.
Syntax
EXECUTE ProcedureName;
Table 2.28:
Parameter Description
ProcedureNameThe 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.
Examples
This statement executes the stored procedure Emp_proc:
EXECUTE Emp_proc ;
2.2.1.11 FETCH
Description
Page 154
Statements, Events, and Functions
Fetches the row after the row on which Cursor | Procedure is positioned.
Syntax
FETCH Cursor | Procedure INTO HostVariableList;
Table 2.29:
Parameter Description
Cursor or The name of the cursor or procedure from which you want to fetch a row
Procedure
HostVariableListPowerScript 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
2.2.1.12 INSERT
Description
Inserts one or more new rows into the table specified in RestOfInsertStatement.
Syntax
Page 155
Statements, Events, and Functions
INSERT RestOfInsertStatement
{USING TransactionObject} ;
Table 2.30:
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).
Usage
Error handling
It is good practice to test the success/failure code after executing an INSERT
statement.
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 ;
Table 2.31:
Parameter Description
CursorName The name of the cursor you want to open
Page 156
Statements, Events, and Functions
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.
Examples
This statement opens the cursor Emp_curs:
OPEN Emp_curs ;
2.2.1.14 ROLLBACK
Description
Cancels all database operations in the specified database since the last COMMIT,
ROLLBACK, or CONNECT.
Syntax
ROLLBACK {USING TransactionObject} ;
Table 2.32:
Parameter Description
TransactionObject
The name of the transaction object that identifies the database in which
you want to cancel all operations since the last COMMIT, ROLLBACK, or
CONNECT. This clause is required only for transaction objects other than the
default (SQLCA).
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:
Page 157
Statements, Events, and Functions
2.2.1.15 SELECT
Description
Selects a row in the tables specified in RestOfSelectStatement.
Syntax
SELECT RestOfSelectStatement {USING TransactionObject} ;
Table 2.33:
Parameter Description
RestOfSelectStatement
The rest of the SELECT statement (the column list INTO, FROM,
WHERE, and other clauses).
TransactionObjectThe 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 datatype of the
retrieved column matches the datatype of the host variable; it only checks for the existence of
the columns and tables. You are responsible for checking that the datatypes match. Keep in
mind that not all database datatypes are the same as PowerBuilder datatypes.
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)
Page 158
Statements, Events, and Functions
sle_Lname.text = Emp_lname
sle_Fname.text = Emp_fname
2.2.1.16 SELECTBLOB
Description
Selects a single blob column in a row in the table specified in RestOfSelectStatement.
Syntax
SELECTBLOB RestOfSelectStatement {USING TransactionObject} ;
Table 2.34:
Parameter Description
RestOfSelectStatement
The rest of the SELECT statement (the INTO, FROM, and WHERE
clauses).
TransactionObjectThe 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
SAP ASE 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
FROM Employee
WHERE Employee.Emp_Num = 100
USING Emp_tran ;
p_1.SetPicture(Emp_id_pic)
Page 159
Statements, Events, and Functions
The blob Emp_id_pic requires a colon to indicate that it is a host (PowerScript) variable
when you use it in the INTO clause of the SELECTBLOB statement.
2.2.1.17 UPDATE
Description
Updates the rows specified in RestOfUpdateStatement.
Syntax
UPDATE TableName RestOfUpdateStatement {USING TransactionObject} ;
Table 2.35:
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).
TransactionObjectThe 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
Error handling
It is good practice to test the success/failure code after executing a UPDATE
statement. You can test SQLCode for a failure code. However, if nothing matches the
WHERE clause and no rows are updated, SQLCode is still set to zero. To make sure
the update affected at least one row, check the SQLNRows property of the transaction
object.
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 ;
The integer Emp_num and the SingleLineEdit sle_name require a colon to indicate they are
host (PowerScript) variables when you use them in an UPDATE statement.
2.2.1.18 UPDATEBLOB
Description
Page 160
Statements, Events, and Functions
Table 2.36:
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 datatype
of this column must be blob.
BlobVariable A PowerScript variable of the datatype 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).
Usage
Error handling
It is good practice to test the success/failure code after executing an UPDATEBLOB
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 UPDATEBLOB statement.
Database information
SAP ASE 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)
FileClose(fh)
UPDATEBLOB Employee SET emp_pic = :Emp_id_pic
WHERE Emp_num = 100
USING Emp_tran ;
END IF
Page 161
Statements, Events, and Functions
The blob Emp_id_pic requires a colon to indicate it is a host (PowerScript) variable in the
UPDATEBLOB statement.
Table 2.37:
Parameter Description
TableName The name of the table in which you want to
update the row
SetStatement The word SET followed by a comma-
separated list of the form ColumnName =
value
CursorName The name of the cursor in which the table is
referenced
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 ;
Four formats
Page 162
Statements, Events, and Functions
PowerBuilder has four dynamic SQL formats. Each format handles one of the following
situations at compile time:
Table 2.38:
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
Two datatypes
DynamicStagingArea
DynamicStagingArea is a PowerBuilder datatype. 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.
Page 163
Statements, Events, and Functions
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
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
Page 164
Statements, Events, and Functions
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
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
string sql1, sql2
sql1 = "SELECT emp_id FROM department "&
WHERE salary > 90000"
sql2 = "SELECT emp_id FROM department "&
WHERE salary > 20000"
IF deptId = 200 then
PREPARE SQLSA FROM :sql1 USING SQLCA ;
ELSE
PREPARE SQLSA FROM :sql2 USING SQLCA ;
END IF
OPEN DYNAMIC my_cursor ; // my_cursor maps to the
// SELECT that has been
// prepared.
[@rc=] indicates that you want to get the procedure's return value.
Use the keyword OUTPUT or OUT to indicate an output parameter if you want to get the
output parameter's value.
If the BindSPInput database parameter is 0, value1, value2,... can be either PowerBuilder
script variables or literal values. If BindSPInput is 1, value1, value2, ... must be PowerBuilder
script variables. If you specify literal values, the SNC interface returns a runtime error.
When you declare a dynamic SQL statement with a procedure, enter a question mark (?) for
each IN/OUT parameter in the statement. Value substitution is positional. For examples, see
Dynamic SQL Format 3 and 4.
Page 165
Statements, Events, and Functions
Table 2.39:
Parameter Description
SQLStatement A string containing a valid SQL statement. The string can be a string
constant or a PowerBuilder variable preceded by a colon (such as :mysql).
The string must be contained on one line and cannot contain expressions.
TransactionObjectThe name of the transaction object that identifies the database.
(optional)
Examples
These statements create a database table named Trainees. The statements use the string Mysql
to store the CREATE statement.
string MyASE
MyASE = "CREATE TABLE Trainees "&
+"(emp_id integer not null,"&
+"emp_fname char(10) not null, "&
+"emp_lname char(20) not null)"
EXECUTE IMMEDIATE :MyASE ;
These statements assume a transaction object named My_trans exists and is connected:
string MyASE
MyASE="INSERT INTO department Values (1234,"&
+"'Purchasing',1234)"
EXECUTE IMMEDIATE :MyASE USING My_trans ;
Table 2.40:
Parameter Description
DynamicStagingArea
The name of the DynamicStagingArea (usually SQLSA).
If you need a DynamicStagingArea variable other than SQLSA, you must
declare it and instantiate it with the CREATE statement before using it.
Page 166
Statements, Events, and Functions
Parameter Description
SQLStatement A string containing a valid SQL statement. The string can be a string
constant or a PowerBuilder variable preceded by a colon (such as :mysql).
The string must be contained on one line and cannot contain expressions.
Enter a question mark (?) for each parameter in the statement. Value
substitution is positional; reserved word substitution is not allowed.
TransactionObject
The name of the transaction object that identifies the database.
(optional)
ParameterList A comma-separated list of PowerScript variables. Note that PowerScript
(optional) variables are preceded by a colon (:).
Usage
To specify a null value, use the SetNull function.
Examples
These statements prepare a DELETE statement with one parameter in SQLSA and then
execute it using the value of the PowerScript variable Emp_id_var:
INT Emp_id_var = 56
PREPARE SQLSA
FROM "DELETE FROM employee WHERE emp_id=?" ;
EXECUTE SQLSA USING :Emp_id_var ;
These statements prepare an INSERT statement with three parameters in SQLSA and then
execute it using the value of the PowerScript variables Dept_id_var, Dept_name_var, and
Mgr_id_var (note that Mgr_id_var is null):
INT Dept_id_var = 156
INT Mgr_id_var
String Dept_name_var
Dept_name_var = "Department"
SetNull(Mgr_id_var)
PREPARE SQLSA
FROM "INSERT INTO department VALUES (?,?,?)" ;
EXECUTE SQLSA
USING :Dept_id_var,:Dept_name_var,:Mgr_id_var ;
Page 167
Statements, Events, and Functions
INTO HostVariableList ;
CLOSE Cursor | Procedure ;
Table 2.41:
Parameter Description
Cursor or The name of the cursor or procedure you want to use.
Procedure
DynamicStagingArea
The name of the DynamicStagingArea (usually SQLSA).
If you need a DynamicStagingArea variable other than SQLSA, you must
declare it and instantiate it with the CREATE statement before using it.
SQLStatement A string containing a valid SQL SELECT statement The string can be
a string constant or a PowerBuilder variable preceded by a colon (such
as :mysql). The string must be contained on one line and cannot contain
expressions.
Enter a question mark (?) for each parameter in the statement. Value
substitution is positional; reserved word substitution is not allowed.
TransactionObjectThe name of the transaction object that identifies the database.
(optional)
ParameterList A comma-separated list of PowerScript variables. Note that PowerScript
(optional) variables are preceded by a colon (:).
HostVariableList The list of PowerScript variables into which the data values will be
retrieved.
Usage
To specify a null value, use the SetNull function.
The DECLARE statement is not executable and can be declared 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.
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 drop-down list in the Script view,
and select Global Variables, Instance Variables, or Shared Variables from the second drop-
down list. Then, select Paste SQL.
For information about global, instance, shared, and local scope, see Where to declare
variables.
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 ;
Page 168
Statements, Events, and Functions
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
Example 3
These statements perform the same processing as the preceding example but use a database
stored procedure called Emp_select:
// The syntax of emp_select is:
// create procedure emp_select (@stateparm char(2)) as
// SELECT emp_id FROM employee WHERE state=@stateparm.
DECLARE my_proc DYNAMIC PROCEDURE FOR SQLSA ;
integer Emp_id_var
string Emp_state_var
Example 4
These statements are for a stored procedure with a return value for a SQL Native Client
(SNC) connection:
integer var1, ReturnVal
string var2
PREPARE SQLSA FROM "execute @rc = myproc @parm1=?, @parm2=? OUTPUT ";
DECLARE my_proc DYNAMIC PROCEDURE FOR SQLSA ;
CLOSE my_proc ;
Page 169
Statements, Events, and Functions
Table 2.42:
Parameter Description
Cursor or The name of the cursor or procedure you want to use.
Procedure
DynamicStagingArea
The name of the DynamicStagingArea (usually SQLSA).
If you need a DynamicStagingArea variable other than SQLSA, you must
declare it and instantiate it with the CREATE statement before using it.
SQLStatement A string containing a valid SQL SELECT statement. The string can be
a string constant or a PowerBuilder variable preceded by a colon (such
as :mysql). The string must be contained on one line and cannot contain
expressions.
Enter a question mark (?) for each parameter in the statement. Value
substitution is positional; reserved word substitution is not allowed.
TransactionObject
The name of the transaction object that identifies the database.
(optional)
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 drop-down list in the Script view and
Page 170
Statements, Events, and Functions
Global Variables, Instance Variables, or Shared Variables from the second drop-down list,
then select Paste SQL.
For information about global, instance, shared, and local scope, see Where to declare
variables.
Accessing attribute information
When a statement is described into a DynamicDescriptionArea, this information is available
to you in the attributes of that DynamicDescriptionArea variable:
Table 2.43:
Information Attribute
Number of input parameters NumInputs
Array of input parameter types InParmType
Number of output parameters NumOutputs
Array of output parameter types OutParmType
Table 2.44:
GetDynamicDate GetDynamicNumber
GetDynamicDateTime GetDynamicString
GetDynamicDecimal GetDynamicTime
Table 2.45:
TypeBoolean! TypeLong!
TypeByte! TypeLongLong!
TypeDate! TypeReal!
Page 171
Statements, Events, and Functions
TypeDateTime! TypeString!
TypeDecimal! TypeTime!
TypeDouble! TypeUInt!
TypeInteger! TypeULong!
TypeUnknown!
Input parameters
You can set the type and value of each input parameter found in the PREPARE statement.
PowerBuilder populates the SQLDA attribute NumInputs when the DESCRIBE is executed.
You can use this value with the SetDynamicParm function to set the type and value of a
specific input parameter. The input parameters are optional; but if you use them, you should
fill in all the values before executing the OPEN or EXECUTE statement.
Output parameters
You can access the type and value of each output parameter found in the PREPARE
statement. If the database supports output parameter description, PowerBuilder populates
the SQLDA attribute NumOutputs when the DESCRIBE is executed. If the database does
not support output parameter description, PowerBuilder populates the SQLDA attribute
NumOutputs when the FETCH statement is executed.
You can use the number of output parameters in the NumOutputs attribute in functions
to obtain the type of a specific parameter from the output parameter type array in the
OutParmType attribute. When you have the type, you can call the appropriate function after
the FETCH statement to retrieve the output value.
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 datatype by wrapping the CHOOSE CASE statement in a loop and expanding the
CASE statements:
string Stringvar, Sqlstatement
integer Intvar
Long LongVar
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
// a value of the enumerated datatype ParmType
// (such as TypeInteger!, TypeLongLong!, or
// TypeString!).
CHOOSE CASE SQLDA.OutParmType[1]
Page 172
Statements, Events, and Functions
CASE TypeString!
Stringvar = GetDynamicString(SQLDA, 1)
CASE TypeInteger!
Intvar = GetDynamicNumber(SQLDA, 1)
CASE TypeLongLong!
Longvar = GetDynamicDecimal(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, sValue
Sqlstatement = "SELECT emp_fname, emp_lname " &
+ "FROM employee WHERE state = ?"
PREPARE SQLSA FROM :Sqlstatement ;
CLOSE my_cursor ;
Example 3
This example is for a stored procedure with a return value for a SQL Native Client (SNC)
connection:
integer var1, ReturnVal
string var2
PREPARE SQLSA FROM "execute @rc = myproc @parm1=?, @parm2=? OUTPUT ";
Page 173
Statements, Events, and Functions
SetDynamicParm(SQLDA, 1, var1)
SetDynamicParm(SQLDA, 2, var2)
CLOSE my_proc ;
Page 174
Statements, Events, and Functions
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 can 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 cannot supply
additional arguments of your own.
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.
Page 175
Statements, Events, and Functions
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 do not 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 return values
Sometimes you want to perform some processing in an event in a descendant 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.
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 (PowerBuilder Message) 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.
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 datatype in the Event Declaration dialog
box.
The event will never be triggered by user actions or system activity. You trigger the event
yourself in your application's scripts.
For more information
Page 176
Statements, Events, and Functions
If you want to trigger events, including system events, see Syntax for calling PowerBuilder
functions and events for information on the calling syntax.
To learn more about user-defined events, see Section 3.3, “Working with User Events” in
Users Guide.
2.3.2 Activate
Description
Occurs just before the window becomes active.
Event ID
Table 2.47:
Event ID Objects
pbm_activate Window
Arguments
None
Return Values
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
Page 177
Statements, Events, and Functions
2.3.3 AddressChange
Description
Occurs when the frame's address changes.
Event ID
Table 2.48:
Event ID Objects
None WebBrowser controls
Arguments
Table 2.49:
Argument Description
newUrl The frame’s new address.
Return Values
None
See also
CertificateError
DownloadingStart
DownloadingStateChanged
EvaluateJavascriptFinished
NavigationError
NavigationProgressIndex
NavigationStart
NavigationStateChanged
PdfPrintFinished
ResourceRedirect
TitleTextChanged
2.3.4 BeginDownload
Description
Occurs at the beginning of a download procedure
Event ID
Table 2.50:
Event ID Objects
None MLSynchronization, MLSync
Page 178
Statements, Events, and Functions
Arguments
None
Return Values
None
Usage
Use this event to add custom actions at the beginning of the download stage of a
synchronization.
When the MobiLink synchronization server receives data, it updates the consolidated
database, then builds a download stream that contains all relevant changes and sends it
back to the remote site. At the end of each successful synchronization, the consolidated and
remote databases are consistent. Either a whole transaction is synchronized, or none of it is
synchronized. This ensures transactional integrity at each database.
The BeginDownload event marks the beginning of the download transaction.
For a complete list of connection and synchronization events, and examples of their use, see
the MobiLink documentation.
See also
BeginSync
BeginUpload
ConnectMobiLink
2.3.5 BeginDrag
The BeginDrag event has different arguments for different objects:
Table 2.51:
Object See
ListView control Syntax 1
TreeView control Syntax 2
Table 2.52:
Event ID Objects
pbm_lvnbegindrag ListView
Arguments
Page 179
Statements, Events, and Functions
Table 2.53:
Argument Description
index Integer by value (the index of the ListView item being dragged)
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Continue processing
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 ListView'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.
Dragging a ListView item onto another control causes its standard drag events (DragDrop,
DragEnter, DragLeave, and DragWithin) to occur. The standard drag events occur for
ListView when another control is dragged within the borders of the ListView.
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 ListView's DragAuto property is FALSE
This.Drag(Begin!)
This.GetItem(This.SelectedIndex(), &
ilvi_dragged_object)
See also
BeginRightDrag
DragDrop
DragEnter
DragLeave
DragWithin
Page 180
Statements, Events, and Functions
Table 2.54:
Event ID Objects
pbm_tvnbegindrag TreeView
Arguments
Table 2.55:
Argument Description
handle Long by value (handle of the TreeView item being dragged)
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Continue processing
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.
Page 181
Statements, Events, and Functions
Instead of deleting the item from the source TreeView immediately, consider deleting it after
the insertion in the DragDrop event succeeds.
See also
BeginRightDrag
DragDrop
DragEnter
DragLeave
DragWithin
2.3.6 BeginLabelEdit
The BeginLabelEdit event has different arguments for different objects:
Table 2.56:
Object See
ListView control Syntax 1
TreeView control Syntax 2
Table 2.57:
Event ID Objects
pbm_lvnbeginlabeledit ListView
Arguments
Table 2.58:
Argument Description
index Integer by value (the index of the selected ListView item)
Return Values
Long.
Return code choices (specify in a RETURN statement):
Page 182
Statements, Events, and Functions
See also
EndLabelEdit
Table 2.59:
Event ID Objects
pbm_tvnbeginlabeledit TreeView
Arguments
Table 2.60:
Argument Description
handle Long by value (the handle of the selected TreeView item)
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Allow editing of the label
1 -- Prevent editing of the label
Usage
When editing is allowed, a box appears around the label with the text highlighted. The user
can replace or change the existing text.
Examples
This example uses the BeginLabelEdit to display the name of the TreeView item being edited
in a SingleLineEdit:
Page 183
Statements, Events, and Functions
TreeViewItem tvi
This.GetItem(index, tvi)
sle_info.text = "Editing " + string(tvi.label)
See also
EndLabelEdit
2.3.7 BeginLogScan
Description
Occurs before dbmlsync scans the transaction log to assemble the upload data stream.
Event ID
Table 2.61:
Event ID Objects
None MLSync
Arguments
Table 2.62:
Argument Description
rescanlog Boolean indicating whether the log has already been scanned for the
current synchronization.
Return Values
None
Usage
Use this event to add custom actions immediately before the transaction log is scanned for
upload. The following events are triggered while the upload stream is prepared, but before
synchronization begins: BeginLogScan, ProgressInfo, and EndLogScan.
If this is the first time the transaction log has been scanned for this synchronization, the
rescanlog value is false; otherwise it is true. The log is scanned twice when the MobiLink
synchronization server and dbmlsync have different information about where scanning should
begin.
See also
EndLogScan
ProgressIndex
2.3.8 BeginRightDrag
The BeginRightDrag event has different arguments for different objects:
Table 2.63:
Object See
ListView control Syntax 1
Page 184
Statements, Events, and Functions
Object See
TreeView control Syntax 2
Table 2.64:
Event ID Objects
pbm_lvnbeginrightdrag ListView
Arguments
Table 2.65:
Argument Description
index Integer by value (the index of the ListView item being dragged)
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Continue processing
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 ListView'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 BeginRightDrag event script, the
programmer can call the Drag function to begin the drag operation.
Dragging a ListView item onto another control causes its standard drag events (DragDrop,
DragEnter, DragLeave, and DragWithin) to occur. The standard drag events occur for
ListView when another control is dragged within the borders of the ListView.
Examples
See the example for the BeginDrag event. It is also effective for the BeginRightDrag event.
See also
BeginDrag
DragDrop
DragEnter
Page 185
Statements, Events, and Functions
DragLeave
DragWithin
Table 2.66:
Event ID Objects
pbm_tvnbeginrightdrag TreeView
Arguments
Table 2.67:
Argument Description
handle Long by value (the handle of the TreeView item being dragged)
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Continue processing
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 ListView'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 BeginRightDrag 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 its 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
See the example for the BeginDrag event.
See also
BeginDrag
DragDrop
Page 186
Statements, Events, and Functions
DragEnter
DragLeave
DragWithin
2.3.9 BeginSync
Description
Occurs at the beginning of the synchronization.
Event ID
Table 2.68:
Event ID Objects
None MLSynchronization, MLSync
Arguments
Table 2.69:
Argument Description
mlusername Read-only string identifying the MobiLink user name.
pubnames Read-only string identifying the publication to be synchronized. If there
is more than one publication, this is a comma-separated list.
Return Values
None
Usage
Use this event to add custom actions at the beginning of a synchronization. The following
synchronization object events correspond to events occurring on the synchronization
server (in the order displayed): BeginSync, ConnectMobiLink, BeginUpload, EndUpload,
BeginDownload, EndDownload, DisconnectMobiLink, and EndSync.
See also
BeginDownload
BeginUpload
ConnectMobiLink
2.3.10 BeginUpload
Description
Occurs at the beginning of the synchronization upload procedure.
Event ID
Table 2.70:
Event ID Objects
None MLSynchronization, MLSync
Page 187
Statements, Events, and Functions
Arguments
None
Return Values
None
Usage
Use this event to add custom actions immediately before the transmission of the upload to the
MobiLink synchronization server.
The BeginUpload event marks the beginning of the upload transaction. Applicable inserts
and updates to the consolidated database are performed for all remote tables, then rows are
deleted as applicable for all remote tables. After EndUpload, upload changes are committed.
See also
BeginDownload
ConnectMobiLink
EndUpload
2.3.11 CategoryCollapsed
Description
Occurs when the category is collapsed. When the RibbonBar is minimized, the category
will be expanded when the user clicks the category title, and will be collapsed when the user
clicks the title again or clicks outside of the category.
Event ID
Table 2.71:
Event ID Objects
None RibbonBar
Arguments
Table 2.72:
Argument Description
Index Long by value (the index of the currently collapsed category)
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Continue processing
Examples
//Adjust the position and height of dw_1 after RibbonBar is collapsed
dw_1.Y = 464 - 364
dw_1.Height = 400 + 364
Page 188
Statements, Events, and Functions
See also
CategorySelectionChanged
CategorySelectionChanging
CategoryExpanded
ItemUnselected
2.3.12 CategoryExpanded
Description
Occurs when the category is expanded. When the RibbonBar is minimized, the category will
be expanded when the user clicks the category title.
Event ID
Table 2.73:
Event ID Objects
None RibbonBar
Arguments
Table 2.74:
Argument Description
Index Long by value (the index of the currently popup category)
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Continue processing
Examples
//Adjust the position and height of dw_1 after RibbonBar is expanded
dw_1.Height = 400
dw_1.Y = 464
See also
CategorySelectionChanged
CategorySelectionChanging
CategoryCollapsed
ItemUnselected
2.3.13 CategorySelectionChanged
Description
Just after the selection changes to another category. CategorySelectionChanged is triggered
when the category is created and the initial selection is established.
Page 189
Statements, Events, and Functions
Event ID
Table 2.75:
Event ID Objects
None RibbonBar
Arguments
Table 2.76:
Argument Description
OldIndex Long by value (the index of the category that was previously selected)
NewIndex Long by value (the index of the category that has become selected)
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Continue processing
Examples
RibbonCategoryItem lr_Category
//st_status is statictext
If rbb_1.GetCategoryByIndex( NewIndex, lr_Category ) = 1 Then
st_status.Text = "Category:[" + lr_Category.Text + "]"
End If
See also
CategorySelectionChanging
CategoryExpanded
CategoryCollapsed
ItemUnselected
2.3.14 CategorySelectionChanging
Description
Occurs when another category is about to be selected.
Event ID
Table 2.77:
Event ID Objects
None RibbonBar
Arguments
Table 2.78:
Argument Description
OldIndex Long by value (the index of the currently selected category)
Page 190
Statements, Events, and Functions
Argument Description
NewIndex Long by value (the index of the category that is about to be selected)
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Allow the selection to change
1 -- Prevent the selection from changing
Examples
Boolean lb_Auth
lb_Auth = gb_Auth //Global Variable
Choose Case NewIndex
Case 2,3
//Whether to authorize
If lb_Auth Then
Return 0
Else
Return 1
End If
End Choose
See also
CategorySelectionChanged
CategoryExpanded
CategoryCollapsed
ItemUnselected
2.3.15 CertificateError
Description
Occurs when failed to validate the server certificate.
Event ID
Table 2.79:
Event ID Objects
None WebBrowser controls
Arguments
Table 2.80:
Argument Description
errorText The error description.
requestUrl The URL of the server currently being requested.
certificateInfo The certificate information which includes certificate issuer, certificate
subject, certificate expiration time, and certificate PEM encoding.
Page 191
Statements, Events, and Functions
Return Values
0 -- to continue browsing the current page.
1 -- to cancel the browsing of the current page.
Examples
Integer CertificateError(string errorText, string requestUrl, string
certificateInfo)
{
strMessage = "[CERTIFICATE_ERROR_TEXT]: " + "~r~n"
strMessage += "ErrorText : " + errortext + "~r~n"
strMessage += "RequestUrl : " + requesturl + "~r~n"
strMessage += "Certificate : " + certificateInfo + "~r~n"
strMessage += "Yes #to continue browsing the web page. No : to concel browsing the
web page ~r~n"
return Ln_Result
}
See also
AddressChanged
DownloadingStart
DownloadingStateChanged
EvaluateJavascriptFinished
NavigationError
NavigationProgressIndex
NavigationStateChanged
NavigationStart
PdfPrintFinished
ResourceRedirect
TitleTextChanged
2.3.16 Clicked
The Clicked event has different arguments for different objects:
Table 2.81:
Object See
Menus Syntax 1
ListView and Toolbar controls Syntax 2
Tab controls Syntax 3
Page 192
Statements, Events, and Functions
Object See
TreeView controls Syntax 4
Window and progress bar controls Syntax 5
Ribbon controls Syntax 6
Other controls Syntax 7
For information about the DataWindow control's Clicked event, see Section 8.8, “Clicked” in
DataWindow Reference.
Table 2.82:
Event ID Objects
None Menu
Arguments
None
Return Values
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
Page 193
Statements, Events, and Functions
Table 2.83:
Event ID Objects
pbm_lvnclicked ListView
Arguments
Table 2.84:
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.
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Continue processing
Usage
The Clicked event occurs when the user presses the mouse button. The Clicked event can
occur during a double-click, in addition to the DoubleClicked event.
In addition to the Clicked event, ItemChanging and ItemChanged events can occur when the
user clicks on an item that does not already have focus. BeginLabelEdit can occur when the
user clicks on a label of an item that has focus.
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
RightClicked
Page 194
Statements, Events, and Functions
RightDoubleClicked
Arguments
Table 2.86:
Argument Description
index Integer by value (the index of the tab page the user clicked)
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Continue processing
Usage
The Clicked event occurs when the mouse button is released.
When the user clicks in the display area of the Tab control, the tab page user object (not the
Tab control) gets a Clicked event.
The Clicked event can occur during a double-click, in addition to the DoubleClicked event.
In addition to the Clicked event, the SelectionChanging and SelectionChanged events
can occur when the user clicks on a tab page label. If the user presses an arrow key to
change tab pages, the Key event occurs instead of Clicked before SelectionChanging and
SelectionChanged.
Examples
This code makes the tab label bold for the fourth tab page only:
IF index = 4 THEN
This.BoldSelectedText = TRUE
ELSE
This.BoldSelectedText = FALSE
END IF
See also
DoubleClicked
RightClicked
RightDoubleClicked
SelectionChanged
Page 195
Statements, Events, and Functions
SelectionChanging
Table 2.87:
Event ID Objects
pbm_tvnclicked TreeView
Arguments
Table 2.88:
Argument Description
handle Long by value (the handle of the TreeView item the user clicked)
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Continue processing
Usage
The Clicked event occurs when the user presses the mouse button.
The Clicked event can occur during a double-click, in addition to the DoubleClicked event.
In addition to the Clicked event, GetFocus occurs if the control does not already have focus.
Examples
This code in the Clicked event changes the label of the item the user clicked to uppercase:
TreeViewItem ltvi_current
This.GetItem(handle, ltvi_current)
ltvi_current.Label = Upper(ltvi_current.Label)
This.SetItem(handle, ltvi_current)
See also
DoubleClicked
RightClicked
RightDoubleClicked
SelectionChanged
SelectionChanging
Page 196
Statements, Events, and Functions
Occurs when the user clicks in an unoccupied area of the window or progress bar (any area
with no visible, enabled object).
Event ID
Table 2.89:
Event ID Objects
pbm_lbuttonclk Window
pbm_lbuttondwn HProgressBar, VProgressBar
Arguments
Table 2.90:
Argument Description
flags UnsignedLong by value (the modifier keys and mouse buttons that are
pressed).
Values are:
• 4 -- Shift key
• 8 -- Ctrl key
In the Clicked event for windows, 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.
xpos Integer by value (the distance of the pointer from the left edge of the
window workspace or control in pixels).
ypos Integer by value (the distance of the pointer from the top of the window's
workspace or control in pixels).
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Continue processing
Usage
The Clicked event occurs when the user presses the mouse button down in progress bars and
when the user releases the mouse button in windows.
If the user clicks on a control or menu in a window, that object (rather than the window) gets
a Clicked event. No Clicked event occurs when the user clicks the window's title bar.
Page 197
Statements, Events, and Functions
When the user clicks on a window, the window's MouseDown and MouseUp events also
occur.
When the user clicks on a visible disabled control or an invisible enabled control, the window
gets a Clicked event.
Examples
If the user clicks in the upper left corner of the window, this code sets focus to the button
cb_clear:
IF (xpos <= 600 AND ypos <= 600) THEN
cb_clear.SetFocus( )
END IF
See also
DoubleClicked
MouseDown
MouseMove
MouseUp
RButtonDown
Table 2.91:
Argument Description
ItemHandle Long. The handle of the item.
Table 2.92:
Argument Description
ItemHandle Long. The handle of the button the menu is associated with.
Index Long. The index of the menu item clicked.
SubIndex Long. The index of the submenu item clicked. 0 indicates the event is
triggered by the main menu.
Page 198
Statements, Events, and Functions
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Continue processing
Examples
This example is a user event for a tab button. In this example, the Ue_TabButtonClicked user
event must be defined with a long parameter for receiving the handle of TabButton where the
mouse is clicking.
RibbonTabButtonItem lr_TabButton
lr_TabButton.Clicked = "Ue_TabButtonClicked"
This example is a user event for a menu item in the ribbon menu. In this example, the
Ue_MenuClicked user event must be defined with three long parameters for receiving the
handle of the tab/large/small button and the index numbers of the menu and sub menu. Each
menu item can be bound with different events or the same event.
//Ue_MenuClicked user event must have three long parameters for receiving the
//handle of Tab/Large/Small Button and the index number of the menu and
//sub menu. Each MenuItem can bind with different events or the same event.
//In the following example, the same event is bound to get RibbonMenu:
event type long ue_menuclicked(long itemhandle, long index, long subindex);
Integer li_Return
RibbonMenu lr_Menu
RibbonMenuItem lr_MenuItem
Page 199
Statements, Events, and Functions
Return 1
end event
This example is a user event for a master menu item in the application menu. In this example,
the Ue_MasterMenuClicked user event must be defined with three Long parameters for
receiving the handle of the application button and the index numbers of the master menu item
and submenu item. Each menu item can be bound with different events or the same event.
//Ue_MasterMenuClicked user event must have three Long parameters for receiving the
//handle of Application Button and the index numbers of the master menu and
//sub menu. Each MenuItem can bind with different events or the same event.
//In the following example, the same event is bound to get RibbonApplicationMenu:
event type long ue_mastermenuclicked(long itemhandle, long index, long subindex);
Integer li_Return
RibbonApplicationMenu lr_Menu
RibbonMenuItem lr_MenuItem
Return 1
end event
This example is a user event for the recent menu item in the application menu. In this
example, the Ue_RecentMenuClicked user event must be defined with two Long parameters
for receiving the handle of the application button and the index number of the recent menu
item. Each menu item can be bound with different events or the same event.
//Ue_RecentMenuClicked user event must have two Long parameters for receiving the
//handle of Application Button and the index number of Recent Menu.
//Each MenuItem can bind with different events or the same event.
//In the following example, the same event is bound to get RibbonApplicationMenu.
event type long ue_recentmenuclicked(long itemhandle, long index);
Integer li_Return
RibbonApplicationMenu lr_Menu
RibbonMenuItem lr_MenuItem
li_Return = rbb_1.GetMenuByButtonHandle(ItemHandle,lr_Menu)
If li_Return = 1 Then
li_Return = lr_Menu.GetRecentItem(Index,lr_MenuItem)
//...
Else
Return 0
End If
Return 1
end event
See also
Modified
Page 200
Statements, Events, and Functions
Selected
SelectionChanged
Table 2.94:
Event ID Objects
pbm_bnclicked CheckBox, CommandButton, Graph, OLE, Picture, PictureHyperLink,
PictureButton, RadioButton, StaticText, StaticHyperLink
pbm_lbuttondownDatePicker, MonthCalendar
Arguments
None
Return Values
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
2.3.17 Close
The Close event has different arguments for different objects:
Table 2.95:
Object See
Application Syntax 1
Page 201
Statements, Events, and Functions
Object See
OLE control Syntax 2
Window Syntax 3
Table 2.96:
Event ID Objects
None Application
Arguments
None
Return Values
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
Table 2.97:
Event ID Objects
pbm_omnclose OLE
Arguments
None
Return Values
Long.
Return code: Ignored
Page 202
Statements, Events, and Functions
Usage
If the user closed the OLE server, the user's choices might cause the OLE object in the
control to be updated, triggering the Save or DataChange 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
Table 2.98:
Event ID Objects
pbm_close Window
Arguments
None
Return Values
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
2.3.18 CloseQuery
Description
Occurs when a window is closed, before the Close event.
Event ID
Page 203
Statements, Events, and Functions
Table 2.99:
Event ID Objects
pbm_closequery Window
Arguments
None
Return Values
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
Page 204
Statements, Events, and Functions
IF li_rc = 1 THEN
Window lw_window
lw_window = w_genapp_frame.GetActiveSheet()
lw_window.TriggerEvent("ue_update")
RETURN 0
//User canceled
ELSE
RETURN 1
END IF
ELSE
// No changes to the data, window will just close
RETURN 0
END IF
See also
Close
2.3.19 CloseUp
Description
Occurs when the user has selected a date from the drop-down calendar and the calendar
closes.
Event ID
Table 2.100:
Event ID Objects
pbm_dtpcloseup DatePicker
Arguments
None.
Return Values
Long.
Return code: Ignored.
2.3.20 ColumnClick
Description
Occurs when the user clicks a column header.
Event ID
Table 2.101:
Event ID Objects
pbm_lvncolumnclick ListView
Page 205
Statements, Events, and Functions
Arguments
Table 2.102:
Argument Description
column The index of the clicked column
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Continue processing
Usage
The ColumnClicked event is only available when the ListView displays in report view and
the ButtonHeader property is set to true.
Examples
This example uses the ColumnClicked event to set up a instance variable for the column
argument, retrieve column alignment information, and display it to the user:
string ls_label, ls_align
integer li_width
alignment la_align
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
See also
Clicked
2.3.21 ConnectMobiLink
Description
Page 206
Statements, Events, and Functions
Occurs when the MobiLink synchronization server connects to the consolidated database
server.
Event ID
Table 2.103:
Event ID Objects
None MLSynchronization, MLSync
Arguments
None
Return Values
None
Usage
When an application forms or reforms a connection with the MobiLink synchronization
server, the MobiLink synchronization server temporarily allocates one connection with the
database server for the duration of that synchronization.
Use the ConnectMobiLink event to add custom actions immediately before the remote
database connects to the MobiLink synchronization server. At this stage, dbmlsync has
generated the upload stream.
The following synchronization object events correspond to events occurring on the
synchronization server (in the order displayed): BeginSync, ConnectMobiLink, BeginUpload,
EndUpload, BeginDownload, EndDownload, DisconnectMobiLink, and EndSync.
See also
BeginDownload
BeginSync
BeginUpload
DisconnectMobiLink
2.3.22 Constructor
Description
Occurs when the control or object is created, just before the Open event for the window that
contains the control.
Event ID
Table 2.104:
Event ID Objects
pbm_constructor All objects
Arguments
None
Return Values
Page 207
Statements, Events, and Functions
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:
• 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
2.3.23 DataChange
Description
Occurs when the server application notifies the control that data has changed.
Event ID
Table 2.105:
Event ID Objects
pbm_omndatachange OLE
Page 208
Statements, Events, and Functions
Arguments
None
Return Values
Long.
Return code: Ignored
See also
PropertyRequestEdit
PropertyChanged
Rename
ViewChange
2.3.24 DateChanged
Description
Occurs immediately after a date is selected.
Event ID
Table 2.106:
Event ID Objects
pbm_mcdatechanged MonthCalendar
Arguments
None
Return Values
Long.
Return code: Ignored
Usage
If you code a call to a MessageBox function in this event, the message box does not display
if the user selects a new date using the mouse. This is because the mouse click captures the
mouse. Message boxes do not display when the mouse is captured because unexpected results
can occur. The message box does display if the user selects a new date using the arrow keys.
SetSelectedDate and SetSelectedRange trigger a DateChanged event. You should not call
either method in a DateChanged event, particularly using the Post method.
See also
DateSelected
2.3.25 DateSelected
Description
Occurs when the user selects a date using the mouse.
Page 209
Statements, Events, and Functions
Event ID
Table 2.107:
Event ID Objects
pbm_mcdatesel MonthCalendar
Arguments
None
Return Values
Long.
Return code: Ignored
Usage
This event is similar to DateChanged, but it occurs only when the user has selected a specific
date using the mouse. The DateChanged event occurs whenever the date changes -- when a
date is selected using the mouse, when the date is changed in a script, and when the user uses
the arrow key on the keyboard to select a different date or the arrow on the control to scroll to
a different month.
Examples
The following script in the DateSelected event writes the date the user selected using the
mouse to a single-line edit box:
date dt_selected
integer li_ret
string ls_date
See also
DateChanged
2.3.26 DBError
Description
Triggered when an error occurs during a transaction or an attempted transaction.
Event ID
Table 2.108:
Event ID Objects
None Transaction objects
Arguments
Table 2.109:
Argument Description
code Long by value. A database-specific error code.
Page 210
Statements, Events, and Functions
Argument Description
See your DBMS documentation for information on the meaning of the
code.
When there is no error code from the DBMS, code contains one of these
values:
-1 -- Cannot connect to the database
-2 -- Writing a blob to the database failed
-4 -- All other errors (see Usage note for more detail)
sqlerrortext String by value. A database-specific error message.
sqlsyntax String by value. The full text of the SQL statement being sent to the
DBMS when the error occurred.
Return Values
Long, but this return code has no meaning to PowerBuilder.
Usage
Error codes
For any database related error, the error code comes from the database driver. The error
text is also from the database drivers. The sqlsyntax argument shows what SQL syntax was
executing when the error occurred.
For errors that are not related to database drivers, the code argument is set to -4. If the
PowerBuilder VM cannot get the syntax for these types of errors, an empty string is passed to
the sqlsyntax argument. PowerBuilder cannot get the syntax for the following types of errors:
Table 2.110:
• "Cursor is not open" • "Cursor is already open"
• "Procedure has not been executed or has • "Procedure has already been executed"
no results"
• "Transaction not connected" • "Transaction already connected"
• "Transaction not connected. Transaction • "Database does not support FETCH
Pool limit exceeded" (FIRST/LAST/PRIOR )"
The PowerBuilder VM can get the SQL syntax for the following types of errors, and passes it
to the Transaction object's DBError event for the following types of errors:
Table 2.111:
• "Select returned more than one row" • "Blob variable for UPDATEBLOB cannot
be empty"
• "Mismatch between prepared number • "Open <cursor> or execute <procedure>
of substitution variables and execute must reference DESCRIPTOR"
parameters"
• "Mismatch between retrieve columns and • "Database does not support WHERE
fetch columns" CURRENT OF <cursor-name>"
Page 211
Statements, Events, and Functions
See also
DBError in Section 8.12, “DBError” in DataWindow Reference
SQLPreview
2.3.27 DBNotification
Description
Triggered by a PowerBuilder script or DataWindow database operation command if a
PowerBuilder database driver receives a notification from the database server. This event is
supported only with the Oracle 10g (O10) native database interface.
Event ID
Table 2.112:
Event ID Objects
pbm_dbnotification Transaction
Arguments
Table 2.113:
Argument Description
notification A value of the DBNotification enumerated datatype. The database
interface determines the type of the notification received from the server,
Page 212
Statements, Events, and Functions
Argument Description
triggers the DBNotification event, and passes the notification type in this
argument. Values are:
Return Values
Long.
Return code choices (specify in a RETURN statement):
• 0 -- Continue to process the database command. If the event does not exist or does not have
a script, the return value is 0 by default.
• Any other value -- Ignored if the notification argument is DBFailover!. If the value of
the notification argument is DBServerDown! or DBDataTruncate!, the current command
returns with an error. SQLCA.SQLCode is set to -1 and SQLCA.SQLDBCode is set to the
return value.
Usage
Oracle Real Application Clusters (RAC) is a cluster database that uses a shared cache
architecture. In Oracle 10g Release 2, a High Availability (HA) client connected to an RAC
database can register a callback to indicate that it wants the server to notify it in case of a
database failure event that affects a connection made by the client. The DBNotification event
is triggered when the client is notified that such an event has occurred.
The default transaction object, SQLCA, does not support this event. To use the event, create
a new standard class user object that inherits from the Transaction object and add code to the
DBNotification event script. You can then use this Transaction object in your application, or
substitute it for SQLCA on the Variable Types tab page in the Application Properties dialog
box.
To be notified when the server shuts down, your application must be connected to an Oracle
10g RAC database using the O10 database interface and the HANotification database
parameter must be set to 1. When the server shuts down, the O10 driver is notified. The
DBNotification event is triggered if the application continues to attempt to access the server.
The value of the notification argument is set to DBServerDown!, the command string is set to
Page 213
Statements, Events, and Functions
the syntax of the current command, and the dbmessage string is populated with information
about the shutdown.
If your application does not execute any SQL statements on the current connection after the
server shuts down, the DBNotification event is not triggered until Disconnect is called.
You can code the return value of the DBNotification event to specify whether the application
should continue to execute the current command:
• If the event returns 0, the current command continues executing until failover occurs and
completes successfully (if failover is supported), then the application continues. If failover
is not supported, the application will receive an error for the current command.
• If the event returns any other value, the current command execution is stopped
immediately and the Transaction object property SQLCode is set to -1, SQLDBCode is set
to the return value, SQLErrText is set to the value of the dbmessage string, and failover
does not happen. After the event, only Disconnect can be called on the current transaction.
Inside the DBNotification event script, the current connection of the Transaction object
is protected and database operations with the connection are not allowed. All database
commands will return as failed. However, the application can still access the database with
another Transaction object.
If the SvrFailover database parameter is set to Yes, the DBNotification event is triggered with
the notification argument set to DBFailover!
The event can be triggered several times during the failover, as when the failover begins
and ends. You do not need to be connected to an Oracle RAC database or to set the
HANotification database parameter to be notified when a failover occurs.
2.3.28 Deactivate
Description
Occurs when the window becomes inactive.
Event ID
Table 2.114:
Event ID Objects
pbm_deactivate Window
Arguments
None
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Continue processing
Usage
When a window is closed, a Deactivate event occurs.
Page 214
Statements, Events, and Functions
See also
Activate
Show
2.3.29 DeleteAllItems
Description
Occurs when all the items in the ListView are deleted.
Event ID
Table 2.115:
Event ID Objects
pbm_lvndeleteallitems ListView
Arguments
None
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Continue processing
Examples
This example uses the DeleteAllItems event to ensure that there is a default item in the
ListView control:
This.AddItem("Default item", 1)
See also
DeleteItem
InsertItem
2.3.30 DeleteItem
The DeleteItem event has different arguments for different objects:
Table 2.116:
Object See
ListView control Syntax 1
TreeView control Syntax 2
Page 215
Statements, Events, and Functions
Table 2.117:
Event ID Objects
pbm_lvndeleteitem ListView
Arguments
Table 2.118:
Argument Description
index Integer by value (the index of the deleted item)
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Continue processing
Examples
This example for the DeleteItem event displays a message with the number of the deleted
item:
MessageBox("Message", "Item " + String(index) &
+ " deleted.")
See also
DeleteAllItems
InsertItem
Arguments
Table 2.120:
Argument Description
handle Long by value (the handle of the deleted item)
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Continue processing
Page 216
Statements, Events, and Functions
Examples
This example displays the name of the deleted item in a message:
TreeViewItem ll_tvi
This.GetItem(handle, ll_tvi)
MessageBox("Message", String(ll_tvi.Label) &
+ " has been deleted.")
2.3.31 Destructor
Description
Occurs when the user object or control is destroyed, immediately after the Close event of a
window.
Event ID
Table 2.121:
Event ID Objects
pbm_destructor All objects
Arguments
None
Return Values
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 have been destroyed, you can no longer refer to those controls in
other scripts. If you do, a runtime error occurs.
See also
Constructor
Close
2.3.32 DisconnectMobiLink
Description
Occurs when the MobiLink synchronization server disconnects from the consolidated
database server.
Event ID
Table 2.122:
Event ID Objects
None MLSynchronization, MLSync
Page 217
Statements, Events, and Functions
Arguments
None
Return Values
None
Usage
Use this event to add custom actions immediately after the remote database disconnects from
the MobiLink synchronization server.
When an application forms or reforms a connection with the MobiLink synchronization
server, the MobiLink synchronization server temporarily allocates one connection with the
database server for the duration of that synchronization.
The following synchronization object events correspond to events occurring on the
synchronization server (in the order displayed): BeginSync, ConnectMobiLink, BeginUpload,
EndUpload, BeginDownload, DisconnectMobiLink, and EndSync.
See also
ConnectMobiLink
EndDownload
EndSync
EndUpload
2.3.33 DisplayMessage
Description
Occurs on display of an informational message from a MobiLink synchronization.
Event ID
Table 2.123:
Event ID Objects
None MLSynchronization, MLSync
Arguments
Table 2.124:
Argument Description
infomsg Read-only string containing the text of an informational message returned
from the synchronization server.
Return Values
None
Usage
The following events are triggered when different types of messages are sent by the
synchronization server: DisplayMessage, ErrorMessage, FileMessage, and WarningMessage.
Page 218
Statements, Events, and Functions
See also
ErrorMessage
FileMessage
WarningMessage
2.3.34 DoubleClicked
The DoubleClicked event has different arguments for different objects:
Table 2.125:
Object See
ListBox, PictureListBox, ListView, and Tab Syntax 1
controls
TreeView control Syntax 2
Window Syntax 3
Other controls Syntax 4
For information about the DataWindow control's DoubleClicked event, see the Section 8.14,
“DoubleClicked” in DataWindow Reference.
Table 2.126:
Event ID Objects
pbm_lbndblclk ListBox, PictureListBox
pbm_lvndoubleclicked ListView
pbm_tcndoubleclicked Tab
Arguments
Table 2.127:
Argument Description
index Integer by value. The index of the item the user double-clicked (for tabs,
the index of the tab page).
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Continue processing
Page 219
Statements, Events, and Functions
Usage
You can use the ItemActivate event (with the OneClickActivate property set to false) instead
of the DoubleClicked event for ListView controls.
In a ListBox or PictureListBox, double-clicking on an item also triggers a SelectionChanged
event.
Examples
This example uses the DoubleClicked event to begin editing the double-clicked ListView
item:
This.EditLabels = TRUE
See also
Clicked
ColumnClick
ItemActivate
ItemChanged
ItemChanging
RightClicked
RightDoubleClicked
SelectionChanged
SelectionChanging
Table 2.128:
Event ID Objects
pbm_tvndoubleclicked TreeView
Arguments
Table 2.129:
Argument Description
handle Long by value (the handle of the item the user double-clicked)
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Continue processing
Page 220
Statements, Events, and Functions
Examples
This example turns on editing for the double-clicked TreeView item:
TreeViewItem ltvi_current
ltvi_current = tv_1.FindItem(CurrentTreeItem!, 0)
This.EditLabel(ltvi_current)
See also
Clicked
RightClicked
RightDoubleClicked
SelectionChanged
SelectionChanging
Table 2.130:
Event ID Objects
pbm_lbuttondblclk Window
Arguments
Table 2.131:
Argument Description
flags UnsignedLong by value (the modifier keys and mouse buttons that are
pressed).
Values are:
• 4 -- Shift key
• 8 -- Ctrl key
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.
Page 221
Statements, Events, and Functions
Argument Description
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).
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Continue processing
Usage
The xpos and ypos arguments provide the same values the functions PointerX and PointerY
return when you call them for the window.
See also
Clicked
MouseDown
MouseMove
MouseUp
RButtonDown
Table 2.132:
Event ID Objects
pbm_bndoubleclicked Graph, OLE, Picture, PictureHyperLink,
StaticText, StaticHyperLink
pbm_cbndblclk DropDownListBox,
DropDownPictureListBox
pbm_lbuttondblclk DatePicker, MonthCalendar
pbm_prndoubleclicked HProgressBar, VProgressBar
pbm_rendoubleclicked RichTextEdit
Arguments
None
Return Values
Long.
Page 222
Statements, Events, and Functions
2.3.35 DownloadingStart
Description
Occurs before a download begins.
Event ID
Table 2.133:
Event ID Objects
None WebBrowser controls
Arguments
Table 2.134:
Argument Description
itemId The ID used to specify the file.
fileName The full path name of the file to be downloaded and saved locally.
Return Values
None
See also
AddressChanged
CertificateError
DownloadingStateChanged
EvaluateJavascriptFinished
NavigationError
NavigationProgressIndex
NavigationStateChanged
NavigationStart
PdfPrintFinished
ResourceRedirect
Page 223
Statements, Events, and Functions
TitleTextChanged
2.3.36 DownloadingStateChanged
Description
Occurs when the download status or progress information has been updated.
Event ID
Table 2.135:
Event ID Objects
None WebBrowser controls
Arguments
Table 2.136:
Argument Description
itemId The ID used to specify the file.
speed The download speed estimated in bytes every second.
received The number of bytes received.
total The total number of bytes to be downloaded.
percent A rough percentage of completion or -1 if the received total size is
unknown.
Return Values
None
Usage
The DownloadingStateChanged event will be triggered for uncertain times even if the
download percentage has reached 100%.
The DownloadingStateChanged event will still be triggered after PauseDownload is called.
See also
AddressChanged
CertificateError
DownloadingStart
EvaluateJavascriptFinished
NavigationError
NavigationProgressIndex
NavigationStart
NavigationStateChanged
PdfPrintFinished
ResourceRedirect
Page 224
Statements, Events, and Functions
TitleTextChanged
2.3.37 DragDrop
The DragDrop event has different arguments for different objects:
Table 2.137:
Object See
ListBox, PictureListBox, ListView, and Tab Syntax 1
controls
TreeView control Syntax 2
Windows and other controls Syntax 3
For information about the DataWindow control's DragDrop event, see the Section 8.15,
“DragDrop” in DataWindow Reference.
Table 2.138:
Event ID Objects
pbm_lbndragdrop ListBox, PictureListBox
pbm_lvndragdrop ListView
pbm_tcndragdrop Tab
Arguments
Table 2.139:
Argument Description
source DragObject by value (a reference to the control being dragged)
index Integer by value (the index of the target ListView item)
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Continue processing
Usage
Obsolete functions
You no longer need to call the DraggedObject function in a drag event. Use the source
argument instead.
Page 225
Statements, Events, and Functions
Examples
For ListView controls, see the example for BeginDrag.
This example inserts the dragged ListView item:
This.AddItem(ilvi_dragged_object)
This.Arrange( )
See also
BeginDrag
BeginRightDrag
DragEnter
DragLeave
DragWithin
Table 2.140:
Event ID Objects
pbm_tvndragdrop TreeView
Arguments
Table 2.141:
Argument Description
source DragObject by value (a reference to the control being dragged)
handle Long by value (the handle of the target TreeView item)
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Continue processing
Usage
Obsolete functions
You no longer need to call the DraggedObject function in a drag event. Use the source
argument instead.
Examples
This example inserts the dragged object as a child of the TreeView item it is dropped upon:
Page 226
Statements, Events, and Functions
TreeViewItem ltv_1
This.GetItem(handle, ltv_1)
This.SetDropHighlight(handle)
This.InsertItemFirst(handle, itvi_drag_object)
This.ExpandItem(handle)
This.SetRedraw(TRUE)
See also
DragEnter
DragLeave
DragWithin
Table 2.142:
Event ID Objects
pbm_bndragdrop CheckBox, CommandButton, Graph, InkEdit, InkPicture, Picture,
PictureHyperLink, PictureButton, RadioButton
pbm_cbndragdrop DropDownListBox, DropDownPictureListBox
pbm_dragdrop DatePicker, MonthCalendar
pbm_endragdrop SingleLineEdit, EditMask, MultiLineEdit, StaticText, StaticHyperLink
pbm_omndragdrop OLE
pbm_prndragdrop HProgressBar, VProgressBar
pbm_rendragdrop RichTextEdit
pbm_sbndragdrop HScrollBar, HTrackBar, VScrollBar, VTrackBar
pbm_uondragdrop UserObject
pbm_dragdrop Window
Arguments
Table 2.143:
Argument Description
source DragObject by value (a reference to the control being dragged)
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Continue processing
Usage
Page 227
Statements, Events, and Functions
When a control's DragAuto property is true, a drag operation begins when the user presses a
mouse button.
Obsolete functions
You no longer need to call the DraggedObject function in a drag event. Use the source
argument instead.
Examples
Example 1
In this example, the code in the DoubleClicked event for the DataWindow dw_orddetail starts
a drag operation:
IF dw_orddetail.GetRow() > 0 THEN
dw_orddetail.Drag(Begin!)
This.DragIcon = "dragitem.ico"
END IF
Then, in the DragDrop event for a trashcan Picture control, this code deletes the row the user
clicked and dragged from the DataWindow control:
long ll_currow
dwitemstatus ldwis_delrow
ll_currow = dw_orddetail.GetRow( )
Example 2
This example for a trashcan Picture control's DragDrop event checks whether the source of
the drag operation is a DataWindow. If so, it asks the user whether to delete the current row
in the source DataWindow:
DataWindow ldw_Source
Long ll_RowToDelete
Integer li_Choice
ldw_Source = source
ll_RowToDelete = ldw_Source.GetRow()
ELSE
Beep(1)
END IF
Page 228
Statements, Events, and Functions
See also
DragEnter
DragLeave
DragWithin
2.3.38 DragEnter
Description
Occurs when the user is dragging an object and enters the control.
Event ID
Table 2.144:
Event ID Objects
pbm_bndragenter CheckBox, CommandButton, Graph, InkEdit, InkPicture, Picture,
PictureHyperlink, PictureButton, RadioButton
pbm_cbndragenterDropDownListBox, DropDownPictureListBox
pbm_dragenter DatePicker, MonthCalendar
pbm_dwndragenterDataWindow
pbm_endragenter SingleLineEdit, EditMask, MultiLineEdit, StaticText, StaticHyperLink
pbm_lbndragenter ListBox, PictureListBox
pbm_lvndragenter ListView
pbm_omndragenterOLE
pbm_prndragenterHProgressBar, VProgressBar
pbm_rendragenter RichTextEdit
pbm_sbndragenterHScrollBar, HTrackBar, VScrollBar, VTrackBar
pbm_tcndragenter Tab
pbm_tvndragenter TreeView
pbm_uondragenterUserObject
pbm_dragenter Window
Arguments
Table 2.145:
Argument Description
source DragObject by value (a reference to the control being dragged)
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Continue processing
Page 229
Statements, Events, and Functions
Usage
Obsolete functions
You no longer need to call the DraggedObject function in a drag event. Use the source
argument instead.
Examples
This example for a Picture control's DragDrop event adds a border to itself when another
Picture control (the source) is dragged within its boundaries:
IF source.TypeOf() = Picture! THEN
This.Border = TRUE
END IF
See also
DragDrop
DragLeave
DragWithin
2.3.39 DragLeave
Description
Occurs when the user is dragging an object and leaves the control.
Event ID
Table 2.146:
Event ID Objects
pbm_bndragleave CheckBox, CommandButton, Graph, InkEdit, InkPicture, Picture,
PictureHyperLink, PictureButton, RadioButton
pbm_cbndragleaveDropDownListBox, DropDownPictureListBox
pbm_dragleave DatePicker, MonthCalendar
pbm_dwndragleaveDataWindow
pbm_endragleave SingleLineEdit, EditMask, MultiLineEdit, StaticText, StaticHyperLink
pbm_lbndragleaveListBox, PictureListBox
pbm_lvndragleaveListView
pbm_omndragleave
OLE
pbm_prndragleaveHProgressBar, VProgressBar
pbm_rendragleaveRichTextEdit
pbm_sbndragleaveHScrollBar, HTrackBar, VScrollBar, VTrackBar
pbm_tcndragleaveTab
pbm_tvndragleaveTreeView
pbm_uondragleaveUserObject
pbm_dragleave Window
Page 230
Statements, Events, and Functions
Arguments
Table 2.147:
Argument Description
source DragObject by value (a reference to the control being dragged)
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Continue processing
Usage
Obsolete functions
You no longer need to call the DraggedObject function in a drag event. Use the source
argument instead.
Examples
This example checks the name of the control being dragged, and if it is, cb_1 it cancels the
drag operation:
IF ClassName(source) = "cb_1" THEN
cb_1.Drag(Cancel!)
END If
This example for a Picture control's DragDrop event removes its own border when another
Picture control (the source) is dragged beyond its boundaries:
IF source.TypeOf() = Picture! THEN
This.Border = TRUE
END IF
See also
DragDrop
DragEnter
DragWithin
2.3.40 DragWithin
The DragWithin event has different arguments for different objects:
Table 2.148:
Object See
ListBox, PictureListBox, ListView, and Tab Syntax 1
controls
TreeView control Syntax 2
Windows and other controls Syntax 3
For information about the DataWindow control's DragWithin event, see Section 8.18,
“DragWithin” in DataWindow Reference.
Page 231
Statements, Events, and Functions
Table 2.149:
Event ID Objects
pbm_lbndragwithin ListBox, PictureListBox
pbm_lvndragwithin ListView
pbm_tcndragwithin Tab
Arguments
Table 2.150:
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)
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Continue processing
Usage
Obsolete functions
You no longer need to call the DraggedObject function in a drag event. Use the source
argument instead.
Examples
This example changes the background color of the ListView when a DragObject enters its
border:
This.BackColor = RGB(128, 0, 128)
See also
DragDrop
DragEnter
DragLeave
Page 232
Statements, Events, and Functions
Event ID
Table 2.151:
Event ID Objects
pbm_tvndragwithin TreeView
Arguments
Table 2.152:
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)
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Continue processing
Usage
Obsolete functions
You no longer need to call the DraggedObject function in a drag event. Use the source
argument instead.
Examples
This example changes the background color of the TreeView when a DragObject enters its
border:
This.BackColor = RGB(128, 0, 128)
See also
DragDrop
DragEnter
DragLeave
Page 233
Statements, Events, and Functions
Event ID Objects
pbm_dragwithin DatePicker, MonthCalendar
pbm_endragwithinSingleLineEdit, EditMask, MultiLineEdit, StaticText, StaticHyperLink
pbm_omndragwithin
OLE
pbm_prndragwithin
HProgressBar, VProgressBar
pbm_rendragwithinRichTextEdit
pbm_sbndragwithin
HScrollBar, HTrackBar, VScrollBar, VTrackBar
pbm_uondragwithin
UserObject
pbm_dragwithin Window
Arguments
Table 2.154:
Argument Description
source DragObject by value (a reference to the control being dragged)
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Continue processing
Usage
Obsolete functions
You no longer need to call the DraggedObject function in a drag event. Use the source
argument instead.
See also
DragDrop
DragEnter
DragLeave
2.3.41 DropDown
Description
Occurs when the user has clicked the drop-down arrow in a DatePicker control just before the
drop-down calendar displays.
Event ID
Table 2.155:
Event ID Objects
pbm_dtpdropdown DatePicker
Arguments
Page 234
Statements, Events, and Functions
None.
Return Values
Long.
Return code: Ignored.
2.3.42 EndDownload
Description
Occurs at the end of a download procedure
Event ID
Table 2.156:
Event ID Objects
None MLSynchronization, MLSync
Arguments
Table 2.157:
Argument Description
upsertrows Long identifying the inserted and updated rows.
deleterows Long identifying the deleted rows.
Return Values
None
Usage
Use this event to add custom actions at the end of the download stage of synchronization.
The BeginDownload event marks the beginning of the download transaction. Applicable
deletes are performed for all remote tables, and then rows are added as applicable for all
remote tables in the download cursor. After EndDownload, download changes are committed.
See also
BeginDownload
ConnectMobiLink
EndSync
EndUpload
2.3.43 EndLabelEdit
The EndLabelEdit event has different arguments for different objects:
Table 2.158:
Object See
ListView control Syntax 1
Page 235
Statements, Events, and Functions
Object See
TreeView control Syntax 2
Table 2.159:
Event ID Objects
pbm_lvnendlabeledit ListView
Arguments
Table 2.160:
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.
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Allow the new text to become the item's label.
1 -- Prevent the new text from becoming the item's label.
Usage
The user triggers this event by pressing Enter or Tab after editing the text.
Examples
This example displays the old label and the new label in a SingleLineEdit:
ListViewItem lvi
sle_info.text = "Finished editing " &
+ String(lvi.label) &
+". Item changed to "+ String(newlabel)
See also
BeginLabelEdit
Page 236
Statements, Events, and Functions
Table 2.161:
Event ID Objects
pbm_tvnendlabeledit TreeView
Arguments
Table 2.162:
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.
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Allow the new text to become the item's label
1 -- Prevent the new text from becoming the item's label
Usage
The user triggers this event by pressing Enter or Tab after editing the text.
Examples
This example displays the old label and the new label in a SingleLineEdit:
TreeViewItem tvi
This.GetItem(handle, tvi)
sle_info.Text = "Finished editing " &
+ String(tvi.Label) &
+ ". Item changed to " &
+ String(newtext)
See also
BeginLabelEdit
2.3.44 EndLogScan
Description
Occurs after the scan of the transaction log completes for upload.
Event ID
Table 2.163:
Event ID Objects
None MLSync
Arguments
Page 237
Statements, Events, and Functions
None
Return Values
None
Usage
Use this event to add custom actions immediately after the transaction log is scanned for
upload.
The following events are triggered while the upload stream is prepared, but before
synchronization begins: BeginLogScan, ProgressInfo, and EndLogScan.
See also
BeginLogScan
ProgressIndex
2.3.45 EndSync
Description
Occurs at the end of synchronization.
Event ID
Table 2.164:
Event ID Objects
None MLSynchronization, MLSync
Arguments
Table 2.165:
Argument Description
rc Long datatype value that indicates whether a synchronization error
occurred.
restart Boolean value passed by reference that, if true, causes dbmlsync to restart
the synchronization.
Return Values
None
Usage
Use this event to add custom actions when a synchronization is complete.
An rc value of 0 indicates a successful synchronization. When the rc value is anything other
than 0, an error has occurred. If the restart value changes to true, dbmlsync restarts the
synchronization.
See also
BeginSync
Page 238
Statements, Events, and Functions
DisconnectMobiLink
EndDownload
EndUpload
2.3.46 EndUpload
Description
Occurs after transmission of the upload to the synchronization server.
Event ID
Table 2.166:
Event ID Objects
None MLSynchronization, MLSync
Arguments
None
Return Values
None
Usage
Use this event to add custom actions immediately after transmission of the upload stream
from dbmlsync to the MobiLink synchronization server.
The BeginUpload event marks the beginning of the upload transaction. Applicable inserts
and updates to the consolidated database are performed for all remote tables, then rows are
deleted as applicable for all remote tables. After EndUpload, upload changes are committed.
See also
BeginUpload
DisconnectMobiLink
EndDownload
EndSync
2.3.47 Error
Page 239
Statements, Events, and Functions
Event ID
Table 2.167:
Event ID Objects
None Connection, DataWindow, DataStore, OLE,
OLEObject, OLETxnObject
Arguments
Table 2.168:
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)
action ExceptionAction by reference.
A value you specify to control the application's course of action as a
result of the error. Values are:
Return Values
Page 240
Statements, Events, and Functions
2. If the Error event has no script or its action argument is set to ExceptionFail!, any active
exception handler for a DWRuntimeError or its RuntimeError ancestor is invoked.
3. If no exception handler exists, or if the existing exception handlers do not handle the
exception, the SystemError event is triggered.
4. If the SystemError event has no script, an application error occurs and the application is
terminated.
The error processing in the client component of a distributed application is the same as for
DataWindows.
For information about error processing in OLE controls, see the ExternalException event. For
information about data and property expressions for DataWindow objects, see Section 5.3,
“PowerBuilder: DataWindow property expressions” in DataWindow Reference.
For information about handling communications errors in a multitier application, see
Chapter 6, Developing Distributed Applications in Application Techniques.
Examples
Page 241
Statements, Events, and Functions
This example displays information about the error that occurred and allows the script to
continue:
MessageBox("Error Number " + string(errornumber)&
+ " Occurred", "Errortext: " + String(errortext))
action = ExceptionIgnore!
See also
DBError in Section 8.12, “DBError” in DataWindow Reference
ExternalException
SystemError
Table 2.169:
Event ID Objects
None CompressorObject
Arguments
Table 2.170:
Argument Description
ErrorNumber Unsigned integer by value (PowerBuilder's error number)
1 -- Success
-1 -- A general error occurred. If the CompressorObject object is used in
asynchronous mode, this function will return the general error.
-2 -- The password entered is illegal.
-3 -- The operation is not supported for the source file format.
-4 -- The task thread is aborted.
-5 -- A task thread is currently running.
-6 -- The folder to be compressed does not exist.
-7 -- The folder to be compressed is empty.
-8 -- The compression format does not support multi-file compression.
-9 -- Failed to read file from the folder for compression.
-10 -- The target path does not exist.
-11 -- More than one source file has the same file name.
-12 -- Invalid compressed file name or no compressed file name is
specified in the "dest" argument.
Page 242
Statements, Events, and Functions
Argument Description
-13 -- Failed to compress.
ErrorText String, read-only (PowerBuilder's error message)
Return Values
None
See also
Finished
ProcessingFile
SizeCompleted
Start
Table 2.171:
Event ID Objects
None ExtractorObject
Arguments
Table 2.172:
Argument Description
ErrorNumber Unsigned integer by value (PowerBuilder's error number)
1 -- Success
-1 -- A general error occurred. If the ExtractorObject object is used in
asynchronous mode, this function will return the general error.
-2 -- The password entered is illegal.
-3 -- The operation is not supported for the source file format.
-4 -- The task thread is aborted.
-5 -- A task thread is currently running.
-6 -- No password is entered. You must enter the password.
-7 -- The password is incorrect.
-8 -- Failed to get new memory when saving the decompressed file.
-9 -- Failed to read the compressed file.
-10 -- Unrecognized format or the encrypted file name option is used
when compressing the document.
Page 243
Statements, Events, and Functions
Argument Description
-11 -- Access denied when extracting the archive.
-12 -- The compressed file does not exist.
-13 -- The directory where the decompressed file will be saved does not
exist.
-14 -- Failed to extract the compressed file.
ErrorText String, read-only (PowerBuilder's error message)
Return Values
None
See also
Finished
ProcessingFile
SizeCompleted
Start
2.3.48 ErrorMessage
Description
Occurs on display of an error message from a MobiLink synchronization.
Event ID
Table 2.173:
Event ID Objects
None MLSynchronization, MLSync
Arguments
Table 2.174:
Argument Description
errmsg Read-only string containing the text of the error message returned from
the synchronization server.
Return Values
None
Usage
Use this event to receive error information logged by dbmlsync.
The following events can be triggered when different types of messages are sent by the
synchronization server: DisplayMessage, ErrorMessage, FileMessage, and WarningMessage.
See also
Page 244
Statements, Events, and Functions
DisplayMessage
FileMessage
WarningMessage
2.3.49 EvaluateJavascriptFinished
Description
Occurs after the EvaluateJavascriptAsync function is executed.
Event ID
Table 2.175:
Event ID Objects
None WebBrowser controls
Arguments
Table 2.176:
Argument Description
result The result of script execution. The execution result is represented in
JSON format. The supported JavaScript data types are bool, int, double,
string, date, array. When the above types are mapped to the PowerBuilder
data types, they are boolean, integer, double, string, datetime, array.
error The error information if an error occurs during execution or an empty
string if there is no error.
Return Values
None
Examples
The following example shows that the EvaluateJavascriptFinished event parses the JavaScript
execution result via the JSONParser object:
//Event EvaluateJavascriptFinished
JsonParser lnv_JsonParser
Long ll_RootObject
String ls_Type
See also
AddressChanged
CertificateError
Page 245
Statements, Events, and Functions
DownloadingStart
DownloadingStateChanged
NavigationError
NavigationProgressIndex
NavigationStart
NavigationStateChanged
PdfPrintFinished
ResourceRedirect
TitleTextChanged
2.3.50 ExternalException
Description
Occurs when an OLE automation command caused an exception on the OLE server.
Event ID
Table 2.177:
Event ID Objects
None OLE, OLEObject, OLETxnObject
Arguments
Table 2.178:
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, which the server provides).
description String by value (a description of the exception, which the server
provides).
helpfile String by value (the name of a Help file containing information about the
exception, which the server provides).
helpcontext UnsignedLong by value (the context ID of a Help topic in helpfile
containing information about the exception, which the server provides).
Page 246
Statements, Events, and Functions
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:
Return Values
None. (Do not use a RETURN statement.)
Usage
OLE objects are dynamic. Expressions that refer to data and properties of these objects might
be valid under some runtime conditions but not others. If the expression causes an exception
on the server, PowerBuilder triggers the ExternalException event. The ExternalException
event gives you information about the error that occurred on the OLE server.
The server defines what it considers exceptions. Some errors, such as mismatched datatypes,
generally do not cause an exception but do trigger the Error event. In some cases you might
not consider the cause of the exception to be an error. To determine the reason for the
exception, see the documentation for the server.
When an exception occurs because of a call to an OLE server, error handling occurs like this:
2. If the ExternalException event has no script or its action argument is set to ExceptionFail!,
the Error event occurs.
3. If the Error event has no script or its action argument is set to ExceptionFail!, any active
exception handler for an OLERuntimeError or its RuntimeError ancestor is invoked.
4. If no exception handler exists, or if the existing exception handlers do not handle the
exception, the SystemError event is triggered.
Page 247
Statements, Events, and Functions
5. If the SystemError event has no script, an application error occurs and the application is
terminated.
Examples
Suppose your window has two instance variables: one for specifying the exception action,
and another of type Any for storing a potential substitute value. Before accessing the OLE
property, a script sets the instance variables to appropriate values:
ie_action = ExceptionSubstituteReturnValue!
ia_substitute = 0
li_currentsetting = ole_1.Object.Value
If the command fails, a script for the ExternalException event displays the Help topic named
by the OLE server, if any. It substitutes the return value you prepared and returns control to
the calling script. The assignment of the substitute value to li_currentsetting works correctly
because their datatypes are compatible:
string ls_context
action = ie_action
returnvalue = ia_substitute
Because the event script must serve for every automation command for the control, you need
to set the instance variables to appropriate values before each automation command.
See also
Error
2.3.51 FileExists
Description
Occurs when a file is saved in the RichTextEdit control and the file already exists.
Event ID
Table 2.179:
Event ID Objects
pbm_renfileexists RichTextEdit
Arguments
Table 2.180:
Argument Description
filename The name of the file
Return Values
Long.
Page 248
Statements, Events, and Functions
2.3.52 FileMessage
Description
Occurs on display of a detailed information message from a MobiLink synchronization.
Event ID
Table 2.181:
Event ID Objects
None MLSynchronization, MLSync
Arguments
Table 2.182:
Argument Description
filemsg Read-only string containing the text of the message returned from the
synchronization server.
Return Values
None
Usage
Use this event to receive information logged by dbmlsync.
The following events can be triggered when different types of messages are sent by the
synchronization server: DisplayMessage, ErrorMessage, FileMessage, and WarningMessage.
Page 249
Statements, Events, and Functions
See also
DisplayMessage
ErrorMessage
WarningMessage
2.3.53 Finished
Description
Occurs when the file compression or extraction is completed.
Event ID
Table 2.183:
Event ID Objects
None CompressorObject and ExtractorObject
Arguments
Table 2.184:
Argument Description
Result A boolean value specifying the file compression or decompression result:
True -- Success
False -- Failed
Return Values
None
See also
Error
ProcessingFile
SizeCompleted
Start
2.3.54 Gesture
Description
Occurs when an application gesture recognized by the control is completed. A gesture is a
stroke or series of strokes that is recognized by the application as indicating an action. This
event can only be triggered on a Tablet PC.
Event ID
Table 2.185:
Event ID Objects
pbm_inkegesture InkEdit
Page 250
Statements, Events, and Functions
Event ID Objects
pbm_inkpgesture InkPicture
Arguments
Table 2.186:
Argument Description
gest Integer identifying the gesture recognized. See the tables in the Usage
section for argument values.
Return Values
Boolean.
Return false to accept the gesture and true to ignore it.
Usage
The Gesture event is triggered only on a Tablet PC. On a Tablet PC, the InkEdit control
recognizes the following gestures that represent keystrokes that are frequently used in edit
controls. To ensure that the gestures are recognized, users should draw straight lines and
sharp right angles without removing the stylus from the control. InkEdit controls on other
computers behave as MultiLineEdit controls and cannot accept ink input from a mouse.
Table 2.187:
Gesture Gesture name Argument value Keystroke
Left 0 Backspace
Right 1 Space
UpRightLong 2 Tab
DownLeftLong 3 Enter
UpRight 4 Tab
DownLeft 5 Enter
On a Tablet PC, the InkPicture control recognizes the following gestures that are equivalent
to mouse clicks:
Table 2.188:
Gesture name Argument value Mouse action
Tap 1 Left Click
Page 251
Statements, Events, and Functions
When you tap the stylus or click a mouse in an InkPicture control on a Tablet PC, the
Gesture event is triggered. On other computers, a mouse click triggers the Stroke event. The
CollectionMode property must be set to GestureOnly! for a double tap to be recognized. Only
single-stroke gestures are recognized when CollectionMode is set to InkAndGesture!. If a
gesture is not recognized, the value of the argument is 0.
Examples
This code in the Gesture event of an InkEdit control confirms to the user that the gesture was
recognized:
CHOOSE CASE gest
CASE 0
MessageBox("Gesture recognized", &
"You entered a space")
CASE 1
MessageBox("Gesture recognized", &
"You entered a backspace")
CASE 2,4
MessageBox("Gesture recognized", &
"You entered a tab")
CASE 3,5
MessageBox("Gesture recognized", &
"You entered a return")
END CHOOSE
return false
See also
RecognitionResult
Stroke
2.3.55 GetFocus
Description
Occurs just before the control receives focus (before it is selected and becomes active).
GetFocus applies to all controls
Event ID
Table 2.189:
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
Page 252
Statements, Events, and Functions
Event ID Objects
pbm_lvnsetfocus ListView
pbm_rensetfocus RichTextEdit
pbm_sbnsetfocus HScrollBar, HTrackBar, VScrollBar, VTrackBar
pbm_setfocus HProgressBar, VProgressBar, DatePicker, MonthCalendar, InkEdit,
InkPicture
pbm_tcnsetfocus Tab
pbm_tvnsetfocus TreeView
Arguments
None
Return Values
Long.
Return code choices (specified 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( )
See also
Clicked
LoseFocus
2.3.56 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
Page 253
Statements, Events, and Functions
Table 2.190:
Event ID Objects
pbm_help Window, Menu, DragObject
Arguments
Table 2.191:
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)
Return Values
Long.
Return code choices (specified in a RETURN statement):
0 -- Continue processing
Usage
The question-mark button only appears in the title bar of response windows. You must set the
ContextHelp property to true to enable this event.
You can script Help messages for individual menu items and controls. PowerBuilder
dispatches the associated Windows message to the appropriate menu item or control.
Examples
This example codes a message box to open when the user drags and clicks the question-mark
button over a TrackBar control:
MessageBox("Context Help Message", "Move the TrackBar" &
+ " slider to~r~n change the DataWindow magnification.")
See also
ShowHelp
2.3.57 Hide
Description
Occurs just before the window is hidden.
Event ID
Table 2.192:
Event ID Objects
pbm_hidewindow Window
Arguments
None
Page 254
Statements, Events, and Functions
Return Values
Long.
Return code choices (specified 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 pop-up window.
See also
Close
Show
2.3.58 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
Table 2.193:
Event ID Objects
pbm_ddedata Window
Arguments
None
Return Values
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)
2.3.59 Idle
Description
Page 255
Statements, Events, and Functions
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
Table 2.194:
Event ID Objects
None Application
Arguments
None
Return Values
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)
2.3.60 InputFieldSelected
Description
In a RichTextEdit control, occurs when the user double-clicks an input field, allowing the
user to edit the data in the field.
Event ID
Table 2.195:
Event ID Objects
pbm_reninputfieldselected RichTextEdit
Arguments
Table 2.196:
Argument Description
fieldname String by value (the name of the input field that was selected)
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Continue processing
Examples
Page 256
Statements, Events, and Functions
This script for the InputFieldSelected event of a RichTextEdit control gets the data in the
input field the user is about to edit:
string ls_fieldvalue
ls_fieldvalue = This.InputFieldGetData(fieldname)
See also
PictureSelected
2.3.61 InsertItem
Description
Occurs when an item is inserted in the ListView.
Event ID
Table 2.197:
Event ID Objects
pbm_lvninsertitem ListView
Arguments
Table 2.198:
Argument Description
index An integer that represents the index of the item being inserted into the
ListView
Return Values
Long.
Return code choices (specified in a RETURN statement):
0 -- Continue processing
Examples
This example displays the label and index of the inserted item:
ListViewItem lvi
This.GetItem(index, lvi)
sle_info.Text = "Inserted "+ String(lvi.Label) &
+ " into position " &
+ String(index)
See also
DeleteItem
2.3.62 ItemActivate
Description
Occurs when a ListView item is clicked or double-clicked. The actual firing mechanism
depends on the OneClickActivate and TwoClickActivate property settings.
Page 257
Statements, Events, and Functions
Event ID
Table 2.199:
Event ID Objects
pbm_lvnitemactivate ListView
Arguments
Table 2.200:
Argument Description
Index An integer that represents the index of the item being inserted into the
ListView
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Continue processing
Usage
Use the ItemActivate event instead of the Clicked or DoubleClicked event in new
applications.
The following ListView property settings determine which user action fires the event:
Table 2.201:
OneClickActivate TwoClickActivate Firing mechanism
True True Single click
True False Single click
False True Single click on selected
item or double-click on
nonselected item
False False Double-click
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
Page 258
Statements, Events, and Functions
ItemChanging
2.3.63 ItemChanged
Description
Occurs when an ListView item has changed.
Event ID
Table 2.202:
Event ID Objects
pbm_lvnitemchanged ListView
Arguments
Table 2.203:
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)
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Continue processing
Examples
This example checks whether the event is occurring because focus has changed to the item:
ListViewItem l_lvi
lv_list.GetItem(index, l_lvi)
IF focuschange and hasfocus THEN
sle1.Text = String(lvi.label) +" has focus."
END IF
See also
ItemChanged in Section 8.27, “ItemChanged” in DataWindow Reference
ItemChanging
2.3.64 ItemChanging
Description
Page 259
Statements, Events, and Functions
Table 2.204:
Event ID Objects
pbm_lvnitemchanging ListView
Arguments
Table 2.205:
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)
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Continue processing
See also
ItemChanged
2.3.65 ItemCollapsed
Description
Occurs when a TreeView item has collapsed.
Event ID
Table 2.206:
Event ID Objects
pbm_tvnitemcollapsed TreeView
Arguments
Table 2.207:
Argument Description
handle Long by reference (the handle of the collapsed TreeViewItem)
Page 260
Statements, Events, and Functions
Return Values
Long.
Return code choices (specified in a RETURN statement):
0 -- Continue processing
Examples
This example changes the picture for the collapsed item:
TreeViewItem l_tvi
integer li_level
This.GetItem(handle, l_tvi)
See also
ItemCollapsing
2.3.66 ItemCollapsing
Description
Occurs when a TreeView item is collapsing.
Event ID
Table 2.208:
Event ID Objects
pbm_tvnitemcollapsing TreeView
Arguments
Table 2.209:
Argument Description
handle Long by reference (the handle of the collapsing item)
Return Values
Long.
Return code choices (specify in a RETURN statement):
Page 261
Statements, Events, and Functions
0 -- Continue processing
Usage
The ItemCollapsing event occurs before the ItemCollapsed event.
Examples
This example changes the picture for the collapsing item:
TreeViewItem l_tvi
integer li_level
This.GetItem(handle, l_vti)
This.SetItem(handle, l_tvi)
See also
ItemCollapsed
2.3.67 ItemExpanded
Description
Occurs when a TreeView item has expanded.
Event ID
Table 2.210:
Event ID Objects
pbm_tvnitemexpanded TreeView
Arguments
Table 2.211:
Argument Description
handle Long by reference (the handle of the expanded item)
Return Values
Long.
Return code choices (specify in a RETURN statement):
Page 262
Statements, Events, and Functions
0 -- Continue processing
Usage
The ItemExpanded event occurs after the ItemExpanding event.
Examples
This example sets the picture and selected picture for the expanded item:
TreeViewItem l_tvi
integer li_level
This.GetItem(handle, l_tvi)
See also
ItemExpanding
2.3.68 ItemExpanding
Description
Occurs while a TreeView item is expanding.
Event ID
Table 2.212:
Event ID Objects
pbm_tvnitemexpanding TreeView
Arguments
Table 2.213:
Argument Description
handle Long by reference (the handle of the expanding TreeView item)
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Continue processing
Page 263
Statements, Events, and Functions
This.GetItem(handle, l_tvi)
This.SetItem(handle, l_tvi)
See also
ItemExpanded
2.3.69 ItemPopulate
Description
Occurs when a TreeView item is being populated with children.
Event ID
Table 2.214:
Event ID Objects
pbm_tvnitempopulate TreeView
Arguments
Table 2.215:
Argument Description
handle Long by reference (the handle of the TreeView item being populated)
Return Values
Long.
Return code choices (specified in a RETURN statement):
Page 264
Statements, Events, and Functions
0 -- Continue processing
Examples
This example displays the name of the TreeView item you are populating in a
SingleLineEdit:
TreeViewItem tvi
This.GetItem(handle, tvi)
sle_get.Text = "Populating TreeView item " &
+ String(tvi.Label) + " with children"
See also
ItemExpanding
2.3.70 ItemUnselected
Description
Occurs when an item changes from highlight to another state.
Event ID
Table 2.216:
Event ID Objects
None RibbonBar
Arguments
None.
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Continue processing
Examples
//st_status is statictext
st_status.Text = "Ready"
See also
CategorySelectionChanged
CategorySelectionChanging
CategoryExpanded
CategoryCollapsed
2.3.71 Key
Description
Occurs when the user presses a key.
Page 265
Statements, Events, and Functions
Event ID
Table 2.217:
Event ID Objects
pbm_lvnkeydown ListView
pbm_renkey RichTextEdit
pbm_tcnkeydown Tab
pbm_tvnkeydown TreeView
pbm_keydown Window
Arguments
Table 2.218:
Argument Description
key KeyCode by value. A value of the KeyCode enumerated datatype
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
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Continue processing
1 -- Do not process the key (RichTextEdit controls only)
Usage
Some PowerBuilder controls capture keystrokes so that the window is prevented from getting
a Key event. These include ListView, TreeView, Tab, RichTextEdit, and the DataWindow
edit control. When these controls have focus you can respond to keystrokes by writing a
script for an event for the control. If there is no predefined event for keystrokes, you can
define a user event and associate it with a pbm code.
For a RichTextEdit control, pressing a key can perform document formatting. For example,
Ctrl+b applies bold formatting to the selection. If you specify a return value of 1, the
document formatting associated with the key will not be performed.
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.
Page 266
Statements, Events, and Functions
When the user releases a key, the Key event does not occur. Therefore, if the user releases
a modifier key, you do not 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
See also
SystemKey
2.3.72 LineDown
Description
Occurs when the user clicks the down arrow of the vertical scroll bar or presses the down
arrow on the keyboard when the focus is on a track bar.
Event ID
Table 2.219:
Event ID Objects
pbm_sbnlinedown VScrollBar, VTrackBar
Arguments
None
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Continue processing
Usage
When the user clicks in a vertical scroll bar or presses the down arrow key with focus in a
vertical track bar, nothing happens unless you have scripts that change the bar's Position
property. For the scroll bar arrows and arrow keys for the track bar, use the LineUp and
LineDown events; for clicks in the scroll bar or track bar background above and below the
thumb, use the PageUp and PageDown event; for dragging the thumb itself, use the Moved
event.
Examples
Page 267
Statements, Events, and Functions
This code in the LineDown event causes the thumb to move down when the user clicks on
the down arrow of the vertical scroll bar 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
See also
LineLeft
LineRight
LineUp
PageDown
2.3.73 LineLeft
Description
Occurs when the user clicks in the left arrow of the horizontal scroll bar or presses the left
arrow key on the keyboard when focus is on a horizontal track bar.
Event ID
Table 2.220:
Event ID Objects
pbm_sbnlineup HScrollBar, HTrackBar
Arguments
None
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Continue processing
Usage
When the user clicks in a horizontal scroll bar or presses the left arrow key on the keyboard
in a horizontal track bar, nothing happens unless you have scripts that change the bar's
Position property. For the scroll bar arrows and left arrow keys in a track bar, use the
LineLeft and LineRight events; for clicks in the 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 scroll bar and displays the resulting position in the StaticText control
st_1:
Page 268
Statements, Events, and Functions
See also
LineDown
LineRight
LineUp
PageLeft
2.3.74 LineRight
Description
Occurs when the user clicks in the right arrow of the horizontal scroll bar or presses the right
arrow key on the keyboard when focus is on a horizontal track bar.
Event ID
Table 2.221:
Event ID Objects
pbm_sbnlinedown HScrollBar, HTrackBar
Arguments
None
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Continue processing
Usage
When the user clicks in a horizontal scroll bar or presses the right arrow key on the keyboard
in a horizontal track bar, nothing happens unless you have scripts that change the bar's
Position property. For the scroll bar arrows and arrow keys in a track bar, use the LineLeft
and LineRight events; for clicks in the 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 LineRight event causes the thumb to move right when the user clicks on the
right arrow of the horizontal scroll bar 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
Page 269
Statements, Events, and Functions
END IF
See also
LineDown
LineLeft
LineUp
PageRight
2.3.75 LineUp
Description
Occurs when the user clicks the up arrow of the vertical scroll bar or presses the up arrow on
the keyboard when the focus is on a track bar
Event ID
Table 2.222:
Event ID Objects
pbm_sbnlineup VScrollBar, VTrackBar
Arguments
None
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Continue processing
Usage
When the user clicks in a vertical scroll bar or presses the up arrow key with focus in a
vertical track bar, nothing happens unless you have scripts that change the bar's Position
property. For the scroll bar arrows and arrow keys for the track bar, use the LineUp and
LineDown events; for clicks in the scroll bar or track bar 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 LineUp event causes the thumb to move up when the user clicks on the up
arrow of the vertical scroll bar 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
Page 270
Statements, Events, and Functions
See also
LineDown
LineLeft
LineRight
PageUp
2.3.76 LoseFocus
Description
Occurs just before a control loses focus (before it becomes inactive).
Event ID
Table 2.223:
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_dwnkillfocusDataWindow
pbm_enkillfocus SingleLineEdit, EditMask, MultiLineEdit
pbm_killfocus HProgressBar, VProgressBar, DatePicker, MonthCalendar, InkEdit,
InkPicture
pbm_lbnkillfocus ListBox, PictureListBox
pbm_lvnkillfocus ListView
pbm_renkillfocus RichTextEdit
pbm_sbnkillfocus HScrollBar, HTrackBar, VScrollBar, VTrackBar
pbm_tcnkillfocus Tab
pbm_tvnkillfocus TreeView
Arguments
None
Return Values
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.
Page 271
Statements, Events, and Functions
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 text box is left empty:
IF sle_town.Text = "" THEN
st_status.Text = "You have not specified a town."
END IF
Example 2
Statements in the LoseFocus event for a DataWindow control dw_emp can trigger a user
event whose script validates the last item the user entered.
This statement triggers the user event ue_accept:
dw_emp.EVENT ue_accept( )
This script for the LoseFocus event of a RichTextEdit control performs processing when the
control actually loses focus:
GraphicObject l_control
See also
GetFocus
2.3.77 Modified
Page 272
Statements, Events, and Functions
This is a user event which occurs when the ribbon combo box control loses focus, the text has
been changed, or Enter or Tab is pressed.
Make sure the parameter (quantities and types) of the user event is correctly defined
according to the requirement of the ribbon combo box control.
Applies to
RibbonComboBoxItem controls
Arguments
Table 2.224:
Argument Description
ItemHandle Long. The handle of the item.
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Continue processing
Example
This example is a user event for a combo box; in this example, the Ue_ComboBoxModified
user event must be defined with a long parameter for receiving the handle of the combo box
that is modified.
//Ue_ComboBoxModified user event must have a long parameter for
//receiving the handle of ComboBox that is modified
event type long ue_comboboxmodified(long itemhandle);
RibbonComboBoxItem lr_ComboBox
rbb_1.GetComboBox(ItemHandle,lr_ComboBox)
//...
return 1
end event
See also
Clicked
Selected
SelectionChanged
Table 2.225:
Event ID Objects
pbm_cbnmodified DropDownListBox,
DropDownPictureListBox
Page 273
Statements, Events, and Functions
Event ID Objects
pbm_enmodified SingleLineEdit, EditMask, MultiLineEdit
pbm_inkemodified InkEdit
pbm_renmodified RichTextEdit
Arguments
None
Return Values
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 InkEdit and 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 text or 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 did not enter RED, WHITE, or BLUE, a
message box indicates 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"
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
Page 274
Statements, Events, and Functions
This is not a realistic example: user input of three specific choices is more suited to a list box;
in a real situation, the allowed input might be more general.
See also
LoseFocus
2.3.78 MouseDown
The MouseDown event has different arguments for different objects:
Table 2.226:
Object See
RichTextEdit control Syntax 1
Window Syntax 2
Table 2.227:
Event ID Objects
pbm_renlbuttondown RichTextEdit
Arguments
None
Return Values
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
Page 275
Statements, Events, and Functions
Occurs when the user presses the left mouse button in an unoccupied area of the window (any
area with no visible, enabled object).
Event ID
Table 2.228:
Event ID Objects
pbm_lbuttondown Window
Arguments
Table 2.229:
Argument Description
flags UnsignedLong by value (the modifier keys and mouse buttons that are
pressed).
Values are:
• 4 -- Shift key
• 8 -- Ctrl key
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Continue processing
Examples
Example 1
This code in the MouseDown event displays the window coordinates of the pointer as
reported in the xpos and ypos arguments:
sle_2.Text = "Position of Pointer is: " + &
String(xpos) + "," + String(ypos)
Page 276
Statements, Events, and Functions
Example 2
This code in the MouseDown event checks the value of the flags argument, and reports which
modifier keys are pressed in the SingleLineEdit sle_modkey:
CHOOSE CASE flags
CASE 1
sle_mkey.Text = "No modifier keys pressed"
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 pressed"
END CHOOSE
See also
Clicked
MouseMove
MouseUp
2.3.79 MouseMove
The MouseMove event has different arguments for different objects:
Table 2.230:
Object See
RichTextEdit control Syntax 1
Window Syntax 2
Table 2.231:
Event ID Objects
pbm_renmousemove RichTextEdit
Arguments
None
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Continue processing
See also
Page 277
Statements, Events, and Functions
Clicked
MouseDown
MouseUp
Table 2.232:
Event ID Objects
pbm_mousemove Window
Arguments
Table 2.233:
Argument Description
flags UnsignedLong by value (the modifier keys and mouse buttons that are
pressed).
Values are:
• 4 -- Shift key
• 8 -- Ctrl key
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).
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Continue processing
Usage
Because flags is a sum of button and key numbers, you can find out what keys are pressed by
subtracting the largest values one by one and checking the value that remains. For example:
Page 278
Statements, Events, and Functions
• If flags is 5, the Shift key (4) and the left mouse button (1) are pressed.
• If flags is 14, the Ctrl key (8), the Shift key (4), and the right mouse button (2) are pressed.
This code handles all the buttons and keys (the local boolean variables are initialized to false
by default):
boolean lb_left_button, lb_right_button
boolean lb_middle_button, lb_Shift_key, lb_control_key
integer li_flags
li_flags = flags
IF li_flags 15 THEN
// Middle button is pressed
lb_middle_button = TRUE
li_flags = li_flags - 16
END IF
IF li_flags 7 THEN
// Control key is pressed
lb_control_key = TRUE
li_flags = li_flags - 8
END IF
Most controls in a window do not capture MouseMove events -- the MouseMove event is
not mapped by default. If you want the window's MouseMove event to be triggered when
the mouse moves over a control, you must map a user-defined event to the pbm_mousemove
event for the control. The following code in the control's user-defined MouseMove event
triggers the window's MouseMove event:
Parent.EVENT MouseMove(0, Parent.PointerX(), Parent.PointerY())
Examples
This code in the MouseMove event causes a meter OLE custom control to rise and fall
continually as the mouse pointer is moved up and down in the window workspace:
This.uf_setmonitor(ypos, ole_verticalmeter, &
This.WorkspaceHeight() )
Uf_setmonitor is a window function that scales the pixels to the range of the gauge. It accepts
three arguments: the vertical position of the mouse pointer, an OLECustomControl reference,
and the maximum range of the mouse pointer for scaling purposes:
double ld_gaugemax, ld_gaugemin
double ld_gaugerange, ld_value
Page 279
Statements, Events, and Functions
// Set gauge
ocxitem.Object.Value = Round(ld_value, 0)
RETURN 1
The OLE custom control also has a MouseMove event. This code in that event keeps the
gauge responding when the pointer is over the gauge. (You need to pass values for the
arguments that are usually handled by the system; the mouse position values are specified in
relation to the parent window.) For example:
Parent.EVENT MouseMove(0, Parent.PointerX(), &
Parent.PointerY())
See also
Clicked
MouseDown
MouseUp
2.3.80 MouseUp
The MouseUp event has different arguments for different objects:
Table 2.234:
Object See
RichTextEdit control Syntax 1
Window Syntax 2
Arguments
None
Return Values
Long.
Return code choices (specify in a RETURN statement):
Page 280
Statements, Events, and Functions
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
Table 2.236:
Event ID Objects
pbm_lbuttonup Window
Arguments
Table 2.237:
Argument Description
flags UnsignedLong by value (the modifier keys and mouse buttons that are
pressed).
Values are:
• 4 -- Shift key
• 8 -- Ctrl key
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.
Page 281
Statements, Events, and Functions
Argument Description
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).
Return Values
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
Example 1
This code in the window's MouseUp event displays in the SingleLineEdit sle_2 the window
coordinates of the pointer when the button is released as reported in the xpos and ypos
arguments.
sle_2.Text = "Position of Pointer is: " + &
String(xpos) + "," + String(ypos)
Example 2
This code in the window's MouseUp event checks the value of the flags argument and reports
which modifier keys are pressed in the SingleLineEdit sle_modkey.
CHOOSE CASE flags
CASE 0
sle_mkey.Text = "No modifier keys pressed"
CASE 4
sle_mkey.Text = "SHIFT key pressed"
CASE 8
sle_mkey.Text = "CONTROL key pressed"
CASE 12
sle_mkey.Text = "SHIFT and CONTROL keys pressed"
END CHOOSE
See also
Clicked
MouseDown
MouseMove
2.3.81 Moved
Description
Page 282
Statements, Events, and Functions
Occurs when the user moves the scroll box, either by clicking on the arrows or by dragging
the box itself.
Event ID
Table 2.238:
Event ID Objects
pbm_sbnthumbtrack HScrollBar, HTrackBar, VScrollBar,
VTrackBar
Arguments
Table 2.239:
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)
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Continue processing
Usage
The Moved event updates the Position property of the scroll bar with the value of scrollpos.
Examples
This statement in the Moved event displays the new position of the scroll box in a StaticText
control:
st_1.Text = "Moved " + String(scrollpos)
See also
LineDown
LineLeft
LineRight
LineUp
PageDown
PageLeft
PageRight
PageUp
2.3.82 NavigationError
Description
Occurs when the navigation fails or is cancelled.
Page 283
Statements, Events, and Functions
Event ID
Table 2.240:
Event ID Objects
None WebBrowser controls
Arguments
Table 2.241:
Argument Description
errorCode The error code number.
errorText The error text.
failedUrl The URL that the browser failed to load.
Return Values
None
See also
AddressChanged
CertificateError
DownloadingStart
DownloadingStateChanged
EvaluateJavascriptFinished
NavigationProgressIndex
NavigationStart
NavigationStateChanged
PdfPrintFinished
ResourceRedirect
TitleTextChanged
2.3.83 NavigationProgressIndex
Description
Occurs when the overall page loading progress changes.
Event ID
Table 2.242:
Event ID Objects
None WebBrowser controls
Arguments
Page 284
Statements, Events, and Functions
Table 2.243:
Argument Description
progressIndex The page loading progress.
Return Values
None
Usage
The NavigationProgressIndex event will be triggered for uncertain times even if the page has
been 100% loaded.
The NavigationProgressIndex event will be triggered if the page's URL has changed.
See also
AddressChanged
CertificateError
DownloadingStart
DownloadingStateChanged
EvaluateJavascriptFinished
NavigationError
NavigationStart
NavigationStateChanged
PdfPrintFinished
ResourceRedirect
TitleTextChanged
2.3.84 NavigationStart
Description
Occurs after a navigation has been committed and before the browser begins loading contents
in the frame.
Event ID
Table 2.244:
Event ID Objects
None WebBrowser controls
Arguments
None
Return Values
None
See also
Page 285
Statements, Events, and Functions
AddressChanged
CertificateError
DownloadingStart
DownloadingStateChanged
EvaluateJavascriptFinished
NavigationError
NavigationProgressIndex
NavigationStateChanged
PdfPrintFinished
ResourceRedirect
TitleTextChanged
2.3.85 NavigationStateChanged
Description
Occurs when the navigation state changes.
Event ID
Table 2.245:
Event ID Objects
None WebBrowser controls
Arguments
Table 2.246:
Argument Description
canGoBack A boolean value specifying whether to be able to go back to the last page:
True -- To be able to go back
False -- Not to able to go back
canGoForward A boolean value specifying whether to be able to move forward to the
next page:
True -- To be able to move forward
False -- Not to be able to move forward
Return Values
None
See also
AddressChanged
CertificateError
DownloadingStart
Page 286
Statements, Events, and Functions
DownloadingStateChanged
EvaluateJavascriptFinished
NavigationError
NavigationProgressIndex
NavigationStart
PdfPrintFinished
ResourceRedirect
TitleTextChanged
2.3.86 Notify
Description
Occurs when a TreeView control sends a WM_NOTIFY message to its parent.
Event ID
Table 2.247:
Event ID Objects
pbm_notify TreeView controls
Arguments
Table 2.248:
Argument Description
wparam UnsignedLong by value containing the ID of the control sending the
message. This value is not guaranteed to be unique.
lparam Long by value containing a pointer to a structure that contains the
window handle and identifier of the control sending a message and a
notification code.
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Continue processing
Usage
The lparam argument can point to an NMHDR structure or to a larger structure that contains
an NMHDR structure as its first member. Since the wparam value is not guaranteed to be
unique, you should use the identifier in the NMHDR structure.
You can use this event to process custom drawing messages.
2.3.87 Open
The Open event has different arguments for different objects:
Page 287
Statements, Events, and Functions
Table 2.249:
Object See
Application Syntax 1
Window Syntax 2
Table 2.250:
Event ID Objects
None Application
Arguments
Table 2.251:
Argument Description
commandline String by value. Additional arguments are included on the command line
after the name of the executable program.
Return Values
None (do not use a RETURN statement)
Usage
This event can establish database connection parameters and open the main window of the
application.
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.
Examples
This example populates the SQLCA global variable from the application's initialization file,
connects to the database, and opens the main window:
/* Populate SQLCA from current myapp.ini settings */
SQLCA.DBMS = ProfileString("myapp.ini", "database", &
"dbms", "")
Page 288
Statements, Events, and Functions
CONNECT;
See also
Close
Table 2.252:
Event ID Objects
pbm_open Window
Arguments
None
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Continue processing
Usage
These functions trigger the Open event:
Open
OpenWithParm
OpenSheet
Page 289
Statements, Events, and Functions
OpenSheetWithParm
When the Open event occurs, the controls on the window already exist (their Constructor
events have occurred). In the Open event script, you can refer to objects in the window and
affect their appearance or content. For example, you can disable a button or retrieve data for a
DataWindow.
Some actions are not appropriate in the Open event, even though all the controls exist. For
example, calling the SetRedraw function for a control fails because the window is not yet
visible.
Closing a window by calling the Close function in any of the window's events or in an event
of any control on the window can cause PowerBuilder to crash if the Close function is not
the last statement in the event script. You can avoid this issue by calling the Close function in
the last statement of the event script, or in a user-defined event that is posted from the event
script. For example, the following code in the Open event script for a window called w_1 can
cause a crash:
// w_1 Open event script
close(this)
open(w_2) // causes crash
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
Page 290
Statements, Events, and Functions
2.3.88 Other
Description
Occurs when a system message occurs that is not a PowerBuilder message.
Event ID
Table 2.253:
Event ID Objects
pbm_other Windows and controls that can be placed in
windows
Arguments
Table 2.254:
Argument Description
wparam UnsignedLong by value
lparam Long by value
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Continue processing
Usage
The Other event is no longer useful, because you can define your own user events. You
should avoid using it, because it slows performance while it checks every Windows message.
2.3.89 PageDown
Description
Occurs when the user clicks in the open space below the scroll box.
Event ID
Table 2.255:
Event ID Objects
pbm_sbnpagedown VScrollBar, VTrackBar
Arguments
None
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Continue processing
Page 291
Statements, Events, and Functions
Usage
When the user clicks in a vertical scroll bar, nothing happens unless you have scripts that
change the scroll bar's Position property. For the scroll bar arrows, use the LineUp and
LineDown events; for clicks in the scroll bar 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 scroll bar 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
See also
LineDown
PageLeft
PageRight
PageUp
2.3.90 PageLeft
Description
Occurs when the open space to the left of the scroll box is clicked.
Event ID
Table 2.256:
Event ID Objects
pbm_sbnpageup HScrollBar, HTrackBar
Arguments
Page 292
Statements, Events, and Functions
None
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Continue processing
Usage
When the user clicks in a horizontal scroll bar, nothing happens unless you have scripts that
change the scroll bar's Position property. For the scroll bar arrows, use the LineLeft and
LineRight events; for clicks in the scroll bar 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 scroll bar (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
2.3.91 PageRight
Description
Occurs when the open space to the right of the scroll box is clicked.
Event ID
Table 2.257:
Event ID Objects
pbm_sbnpagedown HScrollBar, HTrackBar
Arguments
None
Return Values
Long.
Return code choices (specify in a RETURN statement):
Page 293
Statements, Events, and Functions
0 -- Continue processing
Usage
When the user clicks in a horizontal scroll bar, nothing happens unless you have scripts that
change the scroll bar's Position property:
• For the scroll bar arrows, use the LineLeft and LineRight events.
• For clicks in the scroll bar background above and below the thumb, use the PageLeft and
Right 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 scroll bar (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
2.3.92 PageUp
Description
Occurs when the user clicks in the open space above the scroll box (also called the thumb).
Event ID
Table 2.258:
Event ID Objects
pbm_sbnpageup VScrollBar, VTrackBar
Arguments
None
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Continue processing
Page 294
Statements, Events, and Functions
Usage
When the user clicks in a vertical scroll bar, nothing happens unless you have scripts that
change the scroll bar's Position property:
• For the scroll bar arrows, use the LineUp and LineDown events.
• For clicks in the scroll bar background above and below the thumb, use the PageUp and
PageDown events.
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 scroll bar (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
This.Position = This.Position - ii_pagesize
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
2.3.93 PictureSelected
Description
Occurs when the user selects a picture in the RichTextEdit control by clicking it.
Event ID
Table 2.259:
Event ID Objects
pbm_renpictureselected RichTextEdit
Page 295
Statements, Events, and Functions
Arguments
None
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Continue processing
Examples
When the user 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
2.3.94 PipeEnd
Description
Occurs when pipeline processing is completed.
Event ID
Table 2.260:
Event ID Objects
pbm_pipeend Pipeline
Arguments
None
Return Values
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 Section 4.6.2.1, “Building a Pipeline
object” in Application Techniques.
Page 296
Statements, Events, and Functions
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
2.3.95 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
Table 2.261:
Event ID Objects
pbm_pipemeter Pipeline
Arguments
None
Return Values
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 Section 4.6.2.1, “Building a Pipeline
object” in 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
Page 297
Statements, Events, and Functions
2.3.96 PipeStart
Description
Occurs when pipeline processing begins.
Event ID
Table 2.262:
Event ID Objects
pbm_pipestart Pipeline
Arguments
None
Return Values
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 Section 4.6.2.1, “Building a Pipeline
object” in 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
Obsolete event
The PrintHeader and PrintFooter events are obsolete. They are no longer triggered
under any circumstance. You must use the ShowHeadFoot function to edit headers
and footers of pages in a rich text control at runtime.
Event ID
Page 298
Statements, Events, and Functions
Table 2.263:
Event ID Objects
pbm_renprintfooter RichTextEdit
Obsolete event
The PrintHeader and PrintFooter events are obsolete. They are no longer triggered
under any circumstance. You must use the ShowHeadFoot function to edit headers
and footers of pages in a rich text control at runtime.
Event ID
Table 2.264:
Event ID Objects
pbm_renprintheader RichTextEdit
2.3.99 PdfPrintFinished
Description
Occurs when the process of printing PDF is completed.
Event ID
Table 2.265:
Event ID Objects
None WebBrowser controls
Arguments
Table 2.266:
Argument Description
pdfFile The path and file name of the PDF file to be saved.
result The result of operation. TRUE indicates success; FALSE indicates
failure.
Return Values
None
See also
AddressChanged
CertificateError
Page 299
Statements, Events, and Functions
DownloadingStart
DownloadingStateChanged
EvaluateJavascriptFinished
NavigationError
NavigationProgressIndex
NavigationStart
NavigationStateChanged
ResourceRedirect
TitleTextChanged
2.3.100 ProcessingFile
Description
Occurs during the file compression or extraction process. This event can be used to display
the full path name of the file that is being compressed or decompressed.
If one of the files in the compressed archive failed to be extracted, the Error event instead of
the ProcessingFile event will be triggered.
Event ID
Table 2.267:
Event ID Objects
None CompressorObject and ExtractorObject
Arguments
Table 2.268:
Argument Description
FileFullPath A readonly string whose value is the full path name of the file that is
being compressed or decompressed.
Return Values
None
See also
Error
Finished
SizeCompleted
Start
2.3.101 ProgressIndex
Description
Page 300
Statements, Events, and Functions
Table 2.269:
Event ID Objects
None MLSynchronization, MLSync
Arguments
Table 2.270:
Argument Description
progress_idx Long value representing the progress of the synchronization.
progress_max Long value indicating the progress limit of the synchronization.
Return Values
None
Usage
Use this event to update a progress indicator such as a progress bar.
A progress_max value of 0 indicates the maximum value has not changed since the last time
the event was fired.
See also
BeginLogScan
EndLogScan
2.3.102 PropertyChanged
Description
Occurs after the OLE server changes the value of a property of the OLE object.
Event ID
Table 2.271:
Event ID Objects
None OLE
Arguments
Table 2.272:
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.
Return Values
Page 301
Statements, Events, and Functions
2.3.103 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
Table 2.273:
Event ID Objects
None OLE
Arguments
Table 2.274:
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; determines whether the change will be canceled.
Values are:
Return Values
None. Do not use a RETURN statement.
Page 302
Statements, Events, and Functions
Usage
Property change notifications are not supported by all OLE servers. The PropertyRequestEdit
and PropertyChanged events only occur when the server supports these notifications.
Property notifications are not sent when the object is being created or loaded. Otherwise,
notifications are sent for all bindable properties, no matter how the property is being changed.
The PropertyRequestEdit event gives you a chance to access the property's old value using
the automation interface and save it. To cancel the change, set the cancelchange argument to
true.
See also
DataChange
PropertyChanged
Rename
ViewChange
2.3.104 RButtonDown
The RButtonDown event has different arguments for different objects:
Table 2.275:
Object See
Controls and windows, except RichTextEdit Syntax 1
RichTextEdit control Syntax 2
Table 2.276:
Event ID Objects
pbm_rbuttondown Windows and controls that can be placed on
a window, except RichTextEdit
Arguments
Table 2.277:
Argument Description
flags UnsignedLong by value (the modifier keys and mouse buttons that are
pressed).
Page 303
Statements, Events, and Functions
Argument Description
Values are:
• 4 -- Shift key
• 8 -- Ctrl key
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Continue processing
Examples
These statements in the RButtonDown script for the window display a pop-up menu at
the cursor position. Menu4 was created in the Menu painter and includes a menu called
m_language. Menu4 is not the menu for the active window and therefore needs to be created.
NewMenu is an instance of Menu4 (datatype Menu4):
Menu4 NewMenu
NewMenu = CREATE Menu4
NewMenu.m_language.PopMenu(xpos, ypos)
In a Multiple Document Interface (MDI) application, the arguments for PopMenu need to
specify coordinates relative to the MDI frame:
NewMenu.m_language.PopMenu( &
w_frame.PointerX(), w_frame.PointerY())
See also
Clicked
Page 304
Statements, Events, and Functions
Event ID
Table 2.278:
Event ID Objects
pbm_renrbuttondown RichTextEdit
Arguments
None
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Continue processing
Usage
If the control's PopMenu property is true, the standard RichTextEdit pop-up menu is
displayed instead, and the RButtonDown event does not occur.
You can use the RButtonDown event to implement your own pop-up menu.
See also
Clicked
RButtonDown
2.3.105 RButtonUp
Description
Occurs when the right mouse button is released.
Event ID
Table 2.279:
Event ID Objects
pbm_renrbuttonup RichTextEdit
Arguments
None
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Continue processing
1 -- Prevent processing
See also
RButtonDown
Page 305
Statements, Events, and Functions
2.3.106 RecognitionResult
Description
Occurs when an InkEdit control gets results from a call to the RecognizeText function.
Event ID
Table 2.280:
Event ID Objects
pbm_inkerecognition InkEdit
Arguments
None
Return Values
None
Examples
This code in the RecognitionResult event allows the application to wait a few seconds while
the Text property of the ie_id InkEdit control is updated, then writes the recognized text to
the string variable ls_inktext:
Sleep(3)
ls_inktext = ie_id.Text
See also
GetFocus
Stroke
2.3.107 RemoteExec
Description
Occurs when a DDE client application has sent a command.
Event ID
Table 2.281:
Event ID Objects
pbm_ddeexecute Window
Arguments
None
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Continue processing
See also
Page 306
Statements, Events, and Functions
RemoteRequest
RemoteSend
2.3.108 RemoteHotLinkStart
Description
Occurs when a DDE client application wants to start a hot link.
Event ID
Table 2.282:
Event ID Objects
pbm_ddeadvise Window
Arguments
None
Return Values
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 triggers 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
2.3.109 RemoteHotLinkStop
Description
Occurs when a DDE client application wants to end a hot link.
Event ID
Page 307
Statements, Events, and Functions
Table 2.283:
Event ID Objects
pbm_ddeunadvise Window
Arguments
None
Return Values
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 triggers 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
2.3.110 RemoteRequest
Description
Occurs when a DDE client application requests data.
Event ID
Table 2.284:
Event ID Objects
pbm_dderequest Window
Arguments
None
Return Values
Long.
Page 308
Statements, Events, and Functions
2.3.111 RemoteSend
Description
Occurs when a DDE client application has sent data.
Event ID
Table 2.285:
Event ID Objects
pbm_ddepoke Window
Arguments
None
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Continue processing
See also
RemoteExec
RemoteRequest
2.3.112 Rename
Description
Occurs when the server application notifies the control that the object has been renamed.
Event ID
Table 2.286:
Event ID Objects
pbm_omnrename OLE
Arguments
None
Return Values
Long.
Page 309
Statements, Events, and Functions
2.3.113 Resize
Description
Occurs when the user or a script opens or resizes the client area of a window or DataWindow
control.
Event ID
Table 2.287:
Event ID Objects
pbm_dwnresize DataWindow
pbm_size Window
Arguments
Table 2.288:
Argument Description
sizetype UnsignedLong by value. The values are:
Page 310
Statements, Events, and Functions
Argument Description
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).
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Continue processing
2.3.114 ResourceRedirect
Description
Occurs when a resource load is redirected.
Event ID
Table 2.289:
Event ID Objects
None WebBrowser controls
Arguments
Table 2.290:
Argument Description
redirectUrl The new URL to be redirected to.
headers The response headers.
Return Values
None
See also
AddressChanged
CertificateError
DownloadingStart
DownloadingStateChanged
EvaluateJavascriptFinished
NavigationError
NavigationProgressIndex
NavigationStart
NavigationStateChanged
Page 311
Statements, Events, and Functions
PdfPrintFinished
TitleTextChanged
2.3.115 RightClicked
The RightClicked event has different arguments for different objects:
Table 2.291:
Object See
ListView and Tab control Syntax 1
TreeView control Syntax 2
Table 2.292:
Event ID Objects
pbm_lvnrclicked ListView
pbm_tcnrclicked Tab
Arguments
Table 2.293:
Argument Description
index Integer by value (the index of the item or tab the user clicked)
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Continue processing
Usage
When the user clicks in the display area of the Tab control, the tab page user object gets an
RButtonDown event rather than a RightClicked event for the Tab control.
Examples
This example for the RightClicked event of a ListView control displays a pop-up menu when
the user clicks the right mouse button:
// Declare a menu variable of type m_main
m_main m_lv_popmenu
// Create an instance of the menu variable
m_lv_popmenu = CREATE m_main
Page 312
Statements, Events, and Functions
See also
Clicked
RightDoubleClicked
Table 2.294:
Event ID Objects
pbm_tvnrclicked TreeView
Arguments
Table 2.295:
Argument Description
handle Long by value (the handle of the item the user clicked)
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Continue processing
Examples
This example for the RightClicked event of a TreeView control displays a pop-up menu when
the user clicks the right mouse button:
// Declare a menu variable of type m_main
m_main m_tv_popmenu
See also
Clicked
RightDoubleClicked
2.3.116 RightDoubleClicked
The RightDoubleClicked event has different arguments for different objects:
Page 313
Statements, Events, and Functions
Table 2.296:
Object See
ListView and Tab control Syntax 1
TreeView control Syntax 2
Table 2.297:
Event ID Objects
pbm_lvnrdoubleclicked ListView
pbm_tcnrdoubleclicked Tab
Arguments
Table 2.298:
Argument Description
index Integer by value (the index of the item or tab the user double-clicked)
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Continue processing
Examples
This example deletes an item from the ListView when the user right-double-clicks on it and
then rearranges the items:
integer li_rtn
IF li_rtn = 1 THEN
This.Arrange( )
ELSE
MessageBox("Error", Deletion failed!")
END IF
See also
DoubleClicked
RightClicked
Page 314
Statements, Events, and Functions
Table 2.299:
Event ID Objects
pbm_tvnrdoubleclicked TreeView
Arguments
Table 2.300:
Argument Description
handle Long by value (the handle of the item the user double-clicked)
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Continue processing
Examples
This example toggles between displaying and hiding TreeView lines when the user right-
double-clicks on the control:
IF This.HasLines = FALSE THEN
This.HasLines = TRUE
This.LinesAtRoot = TRUE
ELSE
This.HasLines = FALSE
This.LinesAtRoot = FALSE
END IF
See also
DoubleClicked
RightClicked
2.3.117 Save
Description
Occurs when the server application notifies the control that the data has been saved.
Event ID
Table 2.301:
Event ID Objects
pbm_omnsave OLE
Arguments
Page 315
Statements, Events, and Functions
None
Return Values
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 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)
See also
Close
SaveObject
2.3.118 SaveObject
Description
Occurs when the server application saves the object in the control.
Event ID
Table 2.302:
Event ID Objects
pbm_omnsaveobject OLE
Arguments
None
Return Values
Page 316
Statements, Events, and Functions
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 or Excel, 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, the event is triggered
when the display type is DisplayAsContent! but not when it is DisplayAsActiveXDocument!.
Because some servers might also fire the PowerBuilder Save event and the relative timing of
the two events cannot be guaranteed, your program should handle only 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
l_file = FileOpen("c:\myfile.doc", StreamMode!, Write!)
FileWrite( l_file, l_myobjectdata )
FileClose( l_file )
See also
Close
Save
2.3.119 Selected
Page 317
Statements, Events, and Functions
Table 2.303:
Argument Description
ItemHandle Long. The handle of the item.
Table 2.304:
Argument Description
ItemHandle Long. The handle of the button the menu is associated with.
Index Long. The index of the menu item the mouse is on.
SubIndex Long. The index of the submenu item the mouse is on. 0 indicates the
event is triggered by the main menu.
Table 2.305:
Argument Description
ItemHandle Long. The handle of the button the menu is associated with.
Index Long. The index of the menu item the mouse is on.
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Continue processing
Example
This example is a user event for a tab button. In this example, the Ue_TabButtonSelected
user event must be defined with a long parameter for receiving the handle of the tab button
where the mouse is hovering.
RibbonTabButtonItem lr_TabButton
lr_TabButton.Selected = "Ue_TabButtonSelected"
This example is a user event for a menu item in the ribbon menu. In this example, the
Ue_MenuSelected user event must be defined with three long parameters for receiving the
handle of the tab/large/small button and the index numbers of the menu item and submenu
item. Each menu item can be bound with different events or the same event.
//Ue_MenuSelected user event must have three long parameters for receiving the
//handle of Tab/Large/Small Button and the index number of the menu and
Page 318
Statements, Events, and Functions
//sub menu. Each MenuItem can bind with different events or the same event.
//In the following example, the same event is bound to get RibbonMenu:
Return 1
end event
This example is a user event for a master menu item in the application button. In this
example, the Ue_MasterMenuSelected user event must be defined with three Long
parameters for receiving the handle of the application button and the index number of the
master menu item and submenu item. Each menu item can be bound with different events or
the same event.
//Ue_MasterMenuSelected user event must have three Long parameters for receiving
//the handle of Application Button and the index number of the master menu and
//sub menu. Each MenuItem can bind with different events or the same event.
//In the following example, the same event is bound to get RibbonApplicationMenu:
Return 1
end event
This example is a user event for the recent menu item in the application menu. In this
example, the Ue_RecentMenuSelected user event must be defined with two Long parameters
for receiving the handle of the application button and the index number of the recent menu
item. Each menu item can be bound with different events or the same event.
Page 319
Statements, Events, and Functions
//Ue_RecentMenuSelected user event must have two Long parameters for receiving
//the handle of ApplicationButton and the index number of Recent
//Menu. Each MenuItem can bind with different events or the same event.
//In the following example, the same event is bound to get RibbonApplicationMenu.
event type long ue_recentmenuselected(long itemhandle, long index);
Integer li_Return
RibbonApplicationMenu lr_Menu
RibbonMenuItem lr_MenuItem
li_Return = rbb_1.GetMenuByButtonHandle(ItemHandle,lr_Menu)
If li_Return = 1 Then
li_Return = lr_Menu.GetRecentItem(Index,lr_MenuItem)
//...
Else
Return 0
End If
Return 1
end event
See also
Clicked
Modified
SelectionChanged
Table 2.306:
Event ID Objects
None Menu
Arguments
None
Return Values
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:
Page 320
Statements, Events, and Functions
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
2.3.120 SelectionChanged
The SelectionChanged event has different arguments for different objects:
Table 2.307:
Object See
DropDownListBox, Syntax 1
DropDownPictureListBox, ListBox,
PictureListBox controls
Tab control Syntax 2
TreeView control Syntax 3
Ribbon control Syntax 4
Table 2.308:
Event ID Objects
pbm_cbnselchange DropDownListBox,
DropDownPictureListBox
pbm_lbnselchange ListBox, PictureListBox
Arguments
Table 2.309:
Argument Description
index Integer by value (the index of the item that has become selected)
Return Values
Page 321
Statements, Events, and Functions
Long.
Return code choices (specify in a RETURN statement):
0 -- Continue processing
Usage
For DropDownListBoxes, the SelectionChanged event applies to selections in the drop-down
portion of the control, not the edit box.
The SelectionChanged event occurs when the user clicks on any item in the list, even if it is
the currently selected item. When the user makes a selection using the mouse, the Clicked
(and if applicable the DoubleClicked event) occurs after the SelectionChanged event.
Examples
This example is for the lb_value ListBox in the window w_graph_sheet_with_list in the
PowerBuilder Examples application. When the user chooses values, they are graphed as
series in the graph gr_1. The MultiSelect property for the ListBox is set to true, so index has
no effect. The script checks all the items to see if they are selected:
integer itemcount,i,r
string ls_colname
gr_1.SetRedraw(FALSE)
See also
Clicked
Table 2.310:
Event ID Objects
pbm_tcnselchanged Tab
Arguments
Page 322
Statements, Events, and Functions
Table 2.311:
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)
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Continue processing
Usage
The SelectionChanged event occurs when the Tab control is created and the initial selection
is set.
See also
Clicked
SelectionChanging
Table 2.312:
Event ID Objects
pbm_tvnselchanged TreeView
Arguments
Table 2.313:
Argument Description
oldhandle Long by value (the handle of the previously selected item)
newhandle Long by value (the handle of the currently selected item)
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Continue processing
Usage
The SelectionChanged event occurs after the SelectionChanging event.
Examples
This example tracks items in the SelectionChanged event:
Page 323
Statements, Events, and Functions
See also
Clicked
SelectionChanging
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Continue processing
Example
This example is a user event for a combo box. In this example, the
Ue_ComboBoxSelectionChanged user event must be defined with two long parameters for
receiving the handle and index number of the combo box which is selected.
//Ue_ComboBoxSelectionChanged user event must have two long parameters for
//receiving the handle and index number of ComboBox which is selected
event type long ue_comboboxselectionchanged(long itemhandle, long index);
Integer li_Return
String ls_Text
RibbonComboBoxItem lr_ComboBox
li_Return = rbb_1.GetComboBox(ItemHandle,lr_ComboBox)
If li_Return = 1 Then
Page 324
Statements, Events, and Functions
ls_Text = lr_ComboBox.Text(Index)
End If
Return 1
end event
See also
Clicked
Modified
Selected
2.3.121 SelectionChanging
The SelectionChanging event has different arguments for different objects:
Table 2.315:
Object See
Tab control Syntax 1
TreeView control Syntax 2
Table 2.316:
Event ID Objects
pbm_tcnselchanging Tab
Arguments
Table 2.317:
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)
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Allow the selection to change
1 -- Prevent the selection from changing
Usage
Use the SelectionChanging event to prevent the selection from changing or to do processing
for the newly selected tab page before it becomes visible. If CreateOnDemand is true and
Page 325
Statements, Events, and Functions
this is the first time the tab page is selected, the controls on the page do not exist yet, and you
cannot refer to them in the event script.
Examples
When the user selects a tab, this code sizes the DataWindow control on the tab page to match
the size of another DataWindow control. The resizing happens before the tab page becomes
visible. This example is from tab_uo in the w_phone_dir window in the PowerBuilder
Examples:
u_tab_dir luo_Tab
luo_Tab = This.Control[newindex]
luo_Tab.dw_dir.Height = dw_list.Height
luo_Tab.dw_dir.Width = dw_list.Width
See also
Clicked
SelectionChanged
Table 2.318:
Event ID Objects
pbm_tvnselchanging TreeView
Arguments
Table 2.319:
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)
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Allow the selection to change
1 -- Prevent the selection from changing
Usage
The SelectionChanging event occurs before the SelectionChanged event.
Examples
This example displays the status of changing TreeView items in a SingleLineEdit:
TreeViewItem l_tvinew, l_tviold
Page 326
Statements, Events, and Functions
See also
Clicked
SelectionChanged
2.3.122 Show
Description
Occurs just before the window is displayed.
Event ID
Table 2.320:
Event ID Objects
pbm_showwindow Window
Arguments
Table 2.321:
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:
Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Continue processing
Usage
Page 327
Statements, Events, and Functions
2.3.123 SizeCompleted
Description
Occurs during the file compression or extraction process. This event can be used to display
the total number of bytes in the file that has been compressed or decompressed.
Event ID
Table 2.322:
Event ID Objects
None CompressorObject and ExtractorObject
Arguments
Table 2.323:
Argument Description
CompletedSize A longlong whose value is the total number of bytes in the file that has
been compressed or decompressed.
Return Values
None
See also
Error
Finished
ProcessingFile
Start
2.3.124 Sort
The Sort event has different arguments for different objects:
Table 2.324:
Object See
ListView control Syntax 1
TreeView control Syntax 2
Page 328