0% found this document useful (0 votes)
114 views1,596 pages

Powerscript Reference v2019r3

This document provides an overview of PowerScript, the programming language used in Appeon PowerBuilder. It discusses PowerScript basics like comments, identifiers, datatypes and declarations. It also covers statements, functions, events, operators, expressions, structures, objects and calling conventions. The document serves as a reference for the PowerScript language syntax and features.

Uploaded by

Ajay YA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
114 views1,596 pages

Powerscript Reference v2019r3

This document provides an overview of PowerScript, the programming language used in Appeon PowerBuilder. It discusses PowerScript basics like comments, identifiers, datatypes and declarations. It also covers statements, functions, events, operators, expressions, structures, objects and calling conventions. The document serves as a reference for the PowerScript language syntax and features.

Uploaded by

Ajay YA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1596

PowerScript Reference

Appeon PowerBuilder® 2019 R3


Contents
1 PowerScript Topics .............................................................................................. 33
1.1 Language Basics ....................................................................................... 33
1.1.1 Comments ........................................................................................ 33
1.1.2 Identifier names ............................................................................... 34
1.1.3 Labels .............................................................................................. 35
1.1.4 Special ASCII characters ................................................................. 36
1.1.5 NULL values .................................................................................... 37
1.1.6 Reserved words ............................................................................... 39
1.1.7 Pronouns .......................................................................................... 40
1.1.7.1 Parent pronoun ...................................................................... 40
1.1.7.2 This pronoun .......................................................................... 42
1.1.7.3 Super pronoun ....................................................................... 43
1.1.8 Statement continuation .................................................................... 43
1.1.9 Statement separation ....................................................................... 45
1.1.10 White space ................................................................................... 45
1.1.11 Conditional compilation .................................................................. 46
1.2 Datatypes ................................................................................................... 48
1.2.1 Standard datatypes .......................................................................... 48
1.2.2 The Any datatype ............................................................................ 53
1.2.3 System object datatypes ................................................................. 55
1.2.4 Enumerated datatypes ..................................................................... 56
1.3 Declarations ............................................................................................... 56
1.3.1 Declaring variables .......................................................................... 56
1.3.1.1 Where to declare variables ................................................... 57
1.3.1.2 About using variables ............................................................ 58
1.3.1.3 Syntax of a variable declaration ............................................ 60
1.3.2 Declaring constants ......................................................................... 67
1.3.3 Declaring arrays ............................................................................... 68
1.3.3.1 Values for array elements ..................................................... 71
1.3.3.2 Size of variable-size arrays ................................................... 72
1.3.3.3 More about arrays ................................................................. 73
1.3.4 Declaring external functions ............................................................ 76
1.3.4.1 Datatypes for external function arguments ............................ 80
1.3.4.2 Calling external functions ...................................................... 82
1.3.4.3 Defining source for external functions ................................... 82
1.3.5 Declaring DBMS stored procedures as remote procedure calls ...... 83
1.4 Operators and Expressions ....................................................................... 84
1.4.1 Operators in PowerBuilder .............................................................. 85
1.4.1.1 Arithmetic operators in PowerBuilder .................................... 85
1.4.1.2 Relational operators in PowerBuilder .................................... 87
1.4.1.3 Concatenation operator in PowerBuilder ............................... 88
1.4.2 Operator precedence in PowerBuilder expressions ......................... 89
1.4.3 Datatype of PowerBuilder expressions ............................................ 90
1.4.3.1 Numeric datatypes in PowerBuilder ...................................... 90
1.4.3.2 String and char datatypes in PowerBuilder ........................... 92
1.5 Structures and Objects .............................................................................. 93
1.5.1 About structures ............................................................................... 93
1.5.2 About objects ................................................................................... 94
1.5.2.1 About user objects ................................................................. 95
1.5.2.2 Instantiating objects ............................................................... 96
1.5.2.3 Using ancestors and descendants ........................................ 97
1.5.2.4 Garbage collection ................................................................. 97
1.5.2.5 User objects that behave like structures ............................... 98
1.5.3 Assignment for objects and structures ............................................ 99
1.5.3.1 Assignment for structures ...................................................... 99
1.5.3.2 Assignment for objects ........................................................ 100
1.5.3.3 Assignment for autoinstantiated user objects ...................... 100
1.6 Calling Functions and Events .................................................................. 102
1.6.1 About functions and events ........................................................... 102
1.6.2 Finding and executing functions and events ................................. 104
1.6.2.1 Finding functions ................................................................. 104
1.6.2.2 Finding events ..................................................................... 105
1.6.3 Triggering versus posting functions and events ............................ 105
1.6.4 Static versus dynamic calls ........................................................... 107
1.6.4.1 Static calls ........................................................................... 107
1.6.4.2 Dynamic calls ...................................................................... 108
1.6.5 Overloading, overriding, and extending functions and events ....... 112
1.6.5.1 Overloading and overriding functions .................................. 112
1.6.5.2 Extending and overriding events ......................................... 113
1.6.6 Passing arguments to functions and events .................................. 114
1.6.6.1 Passing objects ................................................................... 114
1.6.6.2 Passing structures ............................................................... 115
1.6.6.3 Passing arrays ..................................................................... 115
1.6.7 Using return values ....................................................................... 116
1.6.7.1 Functions ............................................................................. 116
1.6.7.2 Events .................................................................................. 116
1.6.7.3 Using cascaded calling and return values ........................... 117
1.6.8 Syntax for calling PowerBuilder functions and events ................... 117
1.6.9 Calling functions and events in an object's ancestor ..................... 120
2 Statements, Events, and Functions ................................................................... 124
2.1 PowerScript Statements .......................................................................... 124
2.1.1 Assignment .................................................................................... 124
2.1.2 CALL .............................................................................................. 126
2.1.3 CHOOSE CASE ............................................................................ 127
2.1.4 CONTINUE .................................................................................... 128
2.1.5 CREATE ........................................................................................ 129
2.1.6 DESTROY ...................................................................................... 132
2.1.7 DO...LOOP ..................................................................................... 133
2.1.8 EXIT ............................................................................................... 135
2.1.9 FOR...NEXT ................................................................................... 135
2.1.10 GOTO .......................................................................................... 137
2.1.11 HALT ............................................................................................ 138
2.1.12 IF...THEN ..................................................................................... 139
2.1.13 RETURN ...................................................................................... 140
2.1.14 THROW ....................................................................................... 141
2.1.15 THROWS ..................................................................................... 142
2.1.16 TRY...CATCH...FINALLY...END TRY .......................................... 143
2.2 SQL Statements ...................................................................................... 144
2.2.1 Using SQL in scripts ...................................................................... 144
2.2.1.1 CLOSE Cursor ..................................................................... 147
2.2.1.2 CLOSE Procedure ............................................................... 147
2.2.1.3 COMMIT .............................................................................. 148
2.2.1.4 CONNECT ........................................................................... 149
2.2.1.5 DECLARE Cursor ................................................................ 150
2.2.1.6 DECLARE Procedure .......................................................... 150
2.2.1.7 DELETE ............................................................................... 152
2.2.1.8 DELETE Where Current of Cursor ...................................... 152
2.2.1.9 DISCONNECT ..................................................................... 153
2.2.1.10 EXECUTE .......................................................................... 154
2.2.1.11 FETCH ............................................................................... 154
2.2.1.12 INSERT .............................................................................. 155
2.2.1.13 OPEN Cursor ..................................................................... 156
2.2.1.14 ROLLBACK ........................................................................ 157
2.2.1.15 SELECT ............................................................................. 158
2.2.1.16 SELECTBLOB ................................................................... 159
2.2.1.17 UPDATE ............................................................................ 160
2.2.1.18 UPDATEBLOB ................................................................... 160
2.2.1.19 UPDATE Where Current of Cursor ................................... 162
2.2.2 Using dynamic SQL ....................................................................... 162
2.2.2.1 Dynamic SQL Format 1 ....................................................... 165
2.2.2.2 Dynamic SQL Format 2 ....................................................... 166
2.2.2.3 Dynamic SQL Format 3 ....................................................... 167
2.2.2.4 Dynamic SQL Format 4 ....................................................... 170
2.3 PowerScript Events .................................................................................. 174
2.3.1 About events .................................................................................. 174
2.3.2 Activate .......................................................................................... 177
2.3.3 AddressChange ............................................................................. 178
2.3.4 BeginDownload .............................................................................. 178
2.3.5 BeginDrag ...................................................................................... 179
2.3.5.1 Syntax 1: For ListView controls ........................................... 179
2.3.5.2 Syntax 2: For TreeView controls ......................................... 181
2.3.6 BeginLabelEdit ............................................................................... 182
2.3.6.1 Syntax 1: For ListView controls ........................................... 182
2.3.6.2 Syntax 2: For TreeView controls ......................................... 183
2.3.7 BeginLogScan ................................................................................ 184
2.3.8 BeginRightDrag .............................................................................. 184
2.3.8.1 Syntax 1: For ListView controls ........................................... 185
2.3.8.2 Syntax 2: For TreeView controls ......................................... 186
2.3.9 BeginSync ...................................................................................... 187
2.3.10 BeginUpload ................................................................................ 187
2.3.11 CategoryCollapsed ...................................................................... 188
2.3.12 CategoryExpanded ...................................................................... 189
2.3.13 CategorySelectionChanged ......................................................... 189
2.3.14 CategorySelectionChanging ........................................................ 190
2.3.15 CertificateError ............................................................................. 191
2.3.16 Clicked ......................................................................................... 192
2.3.16.1 Syntax 1: For menus ......................................................... 193
2.3.16.2 Syntax 2: For ListView and Toolbar controls ..................... 193
2.3.16.3 Syntax 3: For Tab controls ................................................ 195
2.3.16.4 Syntax 4: For TreeView controls ....................................... 196
2.3.16.5 Syntax 5: For windows and progress bars ........................ 196
2.3.16.6 Syntax 6: For Ribbon controls ........................................... 198
2.3.16.7 Syntax 7: For other controls .............................................. 201
2.3.17 Close ............................................................................................ 201
2.3.17.1 Syntax 1: For the application object .................................. 202
2.3.17.2 Syntax 2: For OLE controls ............................................... 202
2.3.17.3 Syntax 3: For windows ...................................................... 203
2.3.18 CloseQuery .................................................................................. 203
2.3.19 CloseUp ....................................................................................... 205
2.3.20 ColumnClick ................................................................................. 205
2.3.21 ConnectMobiLink ......................................................................... 206
2.3.22 Constructor .................................................................................. 207
2.3.23 DataChange ................................................................................. 208
2.3.24 DateChanged ............................................................................... 209
2.3.25 DateSelected ............................................................................... 209
2.3.26 DBError ........................................................................................ 210
2.3.27 DBNotification .............................................................................. 212
2.3.28 Deactivate .................................................................................... 214
2.3.29 DeleteAllItems .............................................................................. 215
2.3.30 DeleteItem .................................................................................... 215
2.3.30.1 Syntax 1: For ListView controls ......................................... 215
2.3.30.2 Syntax 2: For TreeView controls ....................................... 216
2.3.31 Destructor .................................................................................... 217
2.3.32 DisconnectMobiLink ..................................................................... 217
2.3.33 DisplayMessage ........................................................................... 218
2.3.34 DoubleClicked .............................................................................. 219
2.3.34.1 Syntax 1: For ListBox, PictureListBox, ListView, and Tab
controls ............................................................................................. 219
2.3.34.2 Syntax 2: For TreeView controls ....................................... 220
2.3.34.3 Syntax 3: For windows ...................................................... 221
2.3.34.4 Syntax 4: For other controls .............................................. 222
2.3.35 DownloadingStart ......................................................................... 223
2.3.36 DownloadingStateChanged ......................................................... 224
2.3.37 DragDrop ..................................................................................... 225
2.3.37.1 Syntax 1: For ListBox, PictureListBox, ListView, and Tab
controls ............................................................................................. 225
2.3.37.2 Syntax 2: For TreeView controls ....................................... 226
2.3.37.3 Syntax 3: For windows and other controls ........................ 227
2.3.38 DragEnter ..................................................................................... 229
2.3.39 DragLeave ................................................................................... 230
2.3.40 DragWithin ................................................................................... 231
2.3.40.1 Syntax 1: For ListBox, PictureListBox, ListView, and Tab
controls ............................................................................................. 232
2.3.40.2 Syntax 2: For TreeView controls ....................................... 232
2.3.40.3 Syntax 3: For windows and other controls ........................ 233
2.3.41 DropDown .................................................................................... 234
2.3.42 EndDownload ............................................................................... 235
2.3.43 EndLabelEdit ................................................................................ 235
2.3.43.1 Syntax 1: For ListView controls ......................................... 236
2.3.43.2 Syntax 2: For TreeView controls ....................................... 236
2.3.44 EndLogScan ................................................................................ 237
2.3.45 EndSync ....................................................................................... 238
2.3.46 EndUpload ................................................................................... 239
2.3.47 Error ............................................................................................. 239
2.3.47.1 Syntax 1: for Connection, DataWindow, DataStore, OLE,
OLEObject, OLETxnObject .............................................................. 239
2.3.47.2 Syntax 2: for CompressorObject objects ........................... 242
2.3.47.3 Syntax 3: for ExtractorObject objects ................................ 243
2.3.48 ErrorMessage .............................................................................. 244
2.3.49 EvaluateJavascriptFinished ......................................................... 245
2.3.50 ExternalException ........................................................................ 246
2.3.51 FileExists ...................................................................................... 248
2.3.52 FileMessage ................................................................................. 249
2.3.53 Finished ....................................................................................... 250
2.3.54 Gesture ........................................................................................ 250
2.3.55 GetFocus ..................................................................................... 252
2.3.56 Help .............................................................................................. 253
2.3.57 Hide .............................................................................................. 254
2.3.58 HotLinkAlarm ............................................................................... 255
2.3.59 Idle ............................................................................................... 255
2.3.60 InputFieldSelected ....................................................................... 256
2.3.61 InsertItem ..................................................................................... 257
2.3.62 ItemActivate ................................................................................. 257
2.3.63 ItemChanged ............................................................................... 259
2.3.64 ItemChanging ............................................................................... 259
2.3.65 ItemCollapsed .............................................................................. 260
2.3.66 ItemCollapsing ............................................................................. 261
2.3.67 ItemExpanded .............................................................................. 262
2.3.68 ItemExpanding ............................................................................. 263
2.3.69 ItemPopulate ................................................................................ 264
2.3.70 ItemUnselected ............................................................................ 265
2.3.71 Key ............................................................................................... 265
2.3.72 LineDown ..................................................................................... 267
2.3.73 LineLeft ........................................................................................ 268
2.3.74 LineRight ...................................................................................... 269
2.3.75 LineUp .......................................................................................... 270
2.3.76 LoseFocus ................................................................................... 271
2.3.77 Modified ....................................................................................... 272
2.3.77.1 Syntax 1: For Ribbon controls ........................................... 272
2.3.77.2 Syntax 2: For all other controls ......................................... 273
2.3.78 MouseDown ................................................................................. 275
2.3.78.1 Syntax 1: For RichTextEdit controls .................................. 275
2.3.78.2 Syntax 2: For windows ...................................................... 275
2.3.79 MouseMove ................................................................................. 277
2.3.79.1 Syntax 1: For RichTextEdit controls .................................. 277
2.3.79.2 Syntax 2: For windows ...................................................... 278
2.3.80 MouseUp ...................................................................................... 280
2.3.80.1 Syntax 1: For RichTextEdit controls .................................. 280
2.3.80.2 Syntax 2: For windows ...................................................... 281
2.3.81 Moved .......................................................................................... 282
2.3.82 NavigationError ............................................................................ 283
2.3.83 NavigationProgressIndex ............................................................. 284
2.3.84 NavigationStart ............................................................................ 285
2.3.85 NavigationStateChanged ............................................................. 286
2.3.86 Notify ............................................................................................ 287
2.3.87 Open ............................................................................................ 287
2.3.87.1 Syntax 1: For the application object .................................. 288
2.3.87.2 Syntax 2: For windows ...................................................... 289
2.3.88 Other ............................................................................................ 291
2.3.89 PageDown ................................................................................... 291
2.3.90 PageLeft ....................................................................................... 292
2.3.91 PageRight .................................................................................... 293
2.3.92 PageUp ........................................................................................ 294
2.3.93 PictureSelected ............................................................................ 295
2.3.94 PipeEnd ....................................................................................... 296
2.3.95 PipeMeter ..................................................................................... 297
2.3.96 PipeStart ...................................................................................... 298
2.3.97 PrintFooter (obsolete) .................................................................. 298
2.3.98 PrintHeader (obsolete) ................................................................. 299
2.3.99 PdfPrintFinished ........................................................................... 299
2.3.100 ProcessingFile ........................................................................... 300
2.3.101 ProgressIndex ............................................................................ 300
2.3.102 PropertyChanged ....................................................................... 301
2.3.103 PropertyRequestEdit .................................................................. 302
2.3.104 RButtonDown ............................................................................. 303
2.3.104.1 Syntax 1: For controls and windows, except
RichTextEdit ..................................................................................... 303
2.3.104.2 Syntax 2: For RichTextEdit controls ................................ 304
2.3.105 RButtonUp ................................................................................. 305
2.3.106 RecognitionResult ...................................................................... 306
2.3.107 RemoteExec .............................................................................. 306
2.3.108 RemoteHotLinkStart ................................................................... 307
2.3.109 RemoteHotLinkStop ................................................................... 307
2.3.110 RemoteRequest ......................................................................... 308
2.3.111 RemoteSend .............................................................................. 309
2.3.112 Rename ..................................................................................... 309
2.3.113 Resize ........................................................................................ 310
2.3.114 ResourceRedirect ...................................................................... 311
2.3.115 RightClicked ............................................................................... 312
2.3.115.1 Syntax 1: For ListView and Tab controls ......................... 312
2.3.115.2 Syntax 2: For TreeView controls ..................................... 313
2.3.116 RightDoubleClicked .................................................................... 313
2.3.116.1 Syntax 1: For ListView and Tab controls ......................... 314
2.3.116.2 Syntax 2: For TreeView controls ..................................... 315
2.3.117 Save ........................................................................................... 315
2.3.118 SaveObject ................................................................................ 316
2.3.119 Selected ..................................................................................... 317
2.3.119.1 Syntax 1: For Ribbon controls ......................................... 317
2.3.119.2 Syntax 2: for all other controls ......................................... 320
2.3.120 SelectionChanged ...................................................................... 321
2.3.120.1 Syntax 1: For Listboxes ................................................... 321
2.3.120.2 Syntax 2: For Tab controls .............................................. 322
2.3.120.3 Syntax 3: For TreeView controls ..................................... 323
2.3.120.4 Syntax 4: For Ribbon controls ......................................... 324
2.3.121 SelectionChanging ..................................................................... 325
2.3.121.1 Syntax 1: For Tab controls .............................................. 325
2.3.121.2 Syntax 2: For TreeView controls ..................................... 326
2.3.122 Show .......................................................................................... 327
2.3.123 SizeCompleted ........................................................................... 328
2.3.124 Sort ............................................................................................ 328
2.3.124.1 Syntax 1: For ListView controls ....................................... 328
2.3.124.2 Syntax 2: For TreeView controls ..................................... 330
2.3.125 SQLPreview ............................................................................... 331
2.3.126 Start ........................................................................................... 332
2.3.126.1 Syntax 1: for Animation controls ...................................... 332
2.3.126.2 Syntax 2: for CompressorObject and ExtractorObject
objects .............................................................................................. 332
2.3.127 Stop ............................................................................................ 333
2.3.128 Stroke ......................................................................................... 334
2.3.129 SyncPreview .............................................................................. 334
2.3.130 SystemError ............................................................................... 335
2.3.131 SystemKey ................................................................................. 336
2.3.132 Timer .......................................................................................... 337
2.3.133 TitleTextChanged ....................................................................... 338
2.3.134 ToolbarMoved ............................................................................ 339
2.3.135 UploadAck .................................................................................. 340
2.3.136 UserString .................................................................................. 341
2.3.137 ValueChanged ........................................................................... 342
2.3.138 ViewChange ............................................................................... 343
2.3.139 WaitForUploadAck ..................................................................... 343
2.3.140 WarningMessage ....................................................................... 344
2.4 PowerScript Functions ............................................................................. 344
2.4.1 Abs ................................................................................................. 345
2.4.2 ACos .............................................................................................. 345
2.4.3 AccessToken ................................................................................. 346
2.4.4 Activate .......................................................................................... 347
2.4.5 AddCategory .................................................................................. 348
2.4.6 AddColumn .................................................................................... 350
2.4.7 AddData ......................................................................................... 351
2.4.7.1 Syntax 1: For all graph types except scatter ....................... 351
2.4.7.2 Syntax 2: For scatter graphs ............................................... 352
2.4.8 AddItem .......................................................................................... 353
2.4.8.1 Syntax 1: For ListBox and DropDownListBox controls ........ 353
2.4.8.2 Syntax 2: For PictureListBox, DropDownPictureListBox,
and RibbonComboBoxItem controls ................................................ 355
2.4.8.3 Syntax 3: For ListView controls ........................................... 356
2.4.8.4 Syntax 4: For ListView controls ........................................... 357
2.4.9 AddItemArray ................................................................................. 358
2.4.10 AddItemBlob ................................................................................ 360
2.4.11 AddItemBoolean .......................................................................... 362
2.4.12 AddItemDate ................................................................................ 364
2.4.13 AddItemDateTime ........................................................................ 365
2.4.14 AddItemNull ................................................................................. 369
2.4.15 AddItemNumber ........................................................................... 371
2.4.16 AddItemObject ............................................................................. 374
2.4.17 AddItemString .............................................................................. 376
2.4.18 AddItemTime ................................................................................ 378
2.4.19 AddLargePicture .......................................................................... 379
2.4.20 AddMasterSeparatorItem ............................................................. 380
2.4.21 AddPicture ................................................................................... 382
2.4.22 AddSeparatorItem ........................................................................ 383
2.4.23 AddSeries .................................................................................... 384
2.4.24 AddSmallPicture .......................................................................... 385
2.4.25 AddStatePicture ........................................................................... 386
2.4.26 AddToLibraryList .......................................................................... 387
2.4.27 AppendParam .............................................................................. 388
2.4.28 ApplyTheme ................................................................................. 389
2.4.29 Arrange ........................................................................................ 391
2.4.30 ArrangeSheets ............................................................................. 392
2.4.31 Asc ............................................................................................... 393
2.4.32 AscA ............................................................................................. 394
2.4.33 ASin ............................................................................................. 395
2.4.34 AsymmetricDecrypt ...................................................................... 396
2.4.35 AsymmetricEncrypt ...................................................................... 397
2.4.36 AsymmetricGenerateKey ............................................................. 399
2.4.37 AsymmetricSign ........................................................................... 400
2.4.38 AsymmetricVerifySign .................................................................. 401
2.4.39 ATan ............................................................................................ 403
2.4.40 Base32Decode ............................................................................ 404
2.4.41 Base32Encode ............................................................................. 405
2.4.42 Base64Decode ............................................................................ 406
2.4.43 Base64Encode ............................................................................. 407
2.4.44 Base64UrlDecode ........................................................................ 408
2.4.45 Base64UrlEncode ........................................................................ 409
2.4.46 Beep ............................................................................................. 410
2.4.47 BeginTransaction (obsolete) ........................................................ 410
2.4.48 Blob .............................................................................................. 412
2.4.49 BlobEdit ........................................................................................ 413
2.4.50 BlobMid ........................................................................................ 415
2.4.51 BuildModel ................................................................................... 416
2.4.52 Byte .............................................................................................. 418
2.4.53 Cancel .......................................................................................... 419
2.4.53.1 Syntax 1: for Pipeline objects ............................................ 419
2.4.53.2 Syntax 2: for CompressorObject and ExtractorObject
objects .............................................................................................. 420
2.4.54 CancelDownload .......................................................................... 421
2.4.55 CancelSync .................................................................................. 422
2.4.56 CanUndo ...................................................................................... 422
2.4.57 CategoryCount ............................................................................. 423
2.4.58 CategoryName ............................................................................. 424
2.4.59 Ceiling .......................................................................................... 425
2.4.60 ChangeDirectory .......................................................................... 426
2.4.61 ChangeMenu ............................................................................... 426
2.4.62 Char ............................................................................................. 427
2.4.63 CharA ........................................................................................... 428
2.4.64 Check ........................................................................................... 429
2.4.65 ChooseColor ................................................................................ 430
2.4.66 ClassList ...................................................................................... 430
2.4.67 ClassName .................................................................................. 431
2.4.67.1 Syntax 1: For any object ................................................... 432
2.4.67.2 Syntax 2: For variables ..................................................... 433
2.4.68 Clear ............................................................................................ 433
2.4.68.1 Syntax 1: For selected text ................................................ 434
2.4.68.2 Syntax 2: For RichTextEdit controls .................................. 435
2.4.68.3 Syntax 3: For JSONPackage objects ................................ 436
2.4.69 ClearAll ........................................................................................ 437
2.4.70 ClearBoldDates ............................................................................ 437
2.4.71 ClearHeaders ............................................................................... 438
2.4.71.1 Syntax 1: for TokenRequest objects ................................. 438
2.4.71.2 Syntax 2: for OAuthRequest objects ................................. 439
2.4.72 ClearParams ................................................................................ 440
2.4.73 ClearRecentItems ........................................................................ 440
2.4.74 ClearRequestHeaders .................................................................. 442
2.4.75 Clipboard ...................................................................................... 442
2.4.75.1 Syntax 1: For text .............................................................. 443
2.4.75.2 Syntax 2: For bitmaps of graphs ....................................... 444
2.4.76 Close ............................................................................................ 445
2.4.76.1 Syntax 1: For windows ...................................................... 445
2.4.76.2 Syntax 2: For OLEStorage objects .................................... 446
2.4.76.3 Syntax 3: For OLEStream objects ..................................... 447
2.4.76.4 Syntax 4: For trace files .................................................... 448
2.4.77 CloseChannel .............................................................................. 449
2.4.78 CloseTab ...................................................................................... 450
2.4.79 CloseUserObject .......................................................................... 451
2.4.80 CloseWithReturn .......................................................................... 452
2.4.81 CollapseItem ................................................................................ 454
2.4.82 CommandParm ............................................................................ 455
2.4.83 CommitDocking ............................................................................ 456
2.4.84 CommitTransaction (obsolete) ..................................................... 457
2.4.85 Compress ..................................................................................... 459
2.4.86 ConnectToNewObject .................................................................. 461
2.4.87 ConnectToNewRemoteObject ..................................................... 463
2.4.88 ConnectToObject ......................................................................... 464
2.4.89 ConnectToRemoteObject ............................................................. 467
2.4.90 ConnectToServer (obsolete) ........................................................ 469
2.4.91 ContainsKey ................................................................................. 471
2.4.92 ContainsPath ............................................................................... 473
2.4.93 Copy ............................................................................................. 475
2.4.94 CopyRTF ...................................................................................... 476
2.4.95 Cos ............................................................................................... 478
2.4.96 Cpu .............................................................................................. 479
2.4.97 CreateDirectory ............................................................................ 479
2.4.98 CreateInstance ............................................................................. 480
2.4.98.1 Syntax 1: for TransactionServer objects ............................ 480
2.4.98.2 Syntax 2: for DotNetAssembly objects .............................. 481
2.4.99 CreateJsonArray .......................................................................... 483
2.4.100 CreateJsonObject ...................................................................... 484
2.4.101 CreatePage ................................................................................ 484
2.4.102 Cut ............................................................................................. 485
2.4.103 DataCount .................................................................................. 487
2.4.104 DataSource ................................................................................ 488
2.4.105 Date ........................................................................................... 489
2.4.105.1 Syntax 1: For DateTime data and blobs .......................... 490
2.4.105.2 Syntax 2: For strings ....................................................... 490
2.4.105.3 Syntax 3: For combining numbers into a date ................. 492
2.4.106 DateTime ................................................................................... 493
2.4.106.1 Syntax 1: For creating DateTime values ......................... 493
2.4.106.2 Syntax 2: For extracting DateTime values from blobs ..... 494
2.4.106.3 Syntax 3: For extracting DateTime values from strings ... 494
2.4.107 Day ............................................................................................. 495
2.4.108 DayName ................................................................................... 496
2.4.109 DayNumber ................................................................................ 497
2.4.110 DaysAfter ................................................................................... 498
2.4.111 DBHandle ................................................................................... 499
2.4.112 DebugBreak ............................................................................... 500
2.4.113 Dec ............................................................................................. 500
2.4.114 DeleteCategory .......................................................................... 501
2.4.114.1 Syntax 1: for Graph controls ........................................... 501
2.4.114.2 Syntax 2: for RibbonBar controls ..................................... 502
2.4.115 DeleteCheckBox ........................................................................ 503
2.4.116 DeleteColumn ............................................................................ 504
2.4.117 DeleteColumns .......................................................................... 504
2.4.118 DeleteComboBox ....................................................................... 505
2.4.119 DeleteData ................................................................................. 506
2.4.120 DeleteGroup ............................................................................... 507
2.4.121 DeleteItem .................................................................................. 508
2.4.121.1 Syntax 1: For ListBox, DropDownListBox, and
RibbonComboBoxItem controls ....................................................... 508
2.4.121.2 Syntax 2: For ListView controls ....................................... 509
2.4.121.3 Syntax 3: For TreeView controls ..................................... 510
2.4.121.4 Syntax 4: For RibbonMenu controls ................................ 511
2.4.121.5 Syntax 5: For RibbonBar controls ................................... 512
2.4.122 DeleteItems ................................................................................ 513
2.4.123 DeleteLargeButton ..................................................................... 514
2.4.124 DeleteLargePicture .................................................................... 515
2.4.125 DeleteLargePictures ................................................................... 515
2.4.126 DeleteMasterItem ....................................................................... 516
2.4.127 DeletePanel ............................................................................... 517
2.4.128 DeletePicture ............................................................................. 518
2.4.129 DeletePictures ............................................................................ 519
2.4.130 DeleteRecentItem ...................................................................... 520
2.4.131 DeleteSeries .............................................................................. 521
2.4.132 DeleteSmallButton ..................................................................... 522
2.4.133 DeleteSmallPicture ..................................................................... 523
2.4.134 DeleteSmallPictures ................................................................... 523
2.4.135 DeleteStatePicture ..................................................................... 524
2.4.136 DeleteStatePictures ................................................................... 524
2.4.137 DeleteTabButton ........................................................................ 525
2.4.138 DestroyModel ............................................................................. 526
2.4.139 DirectoryExists ........................................................................... 527
2.4.140 DirList ......................................................................................... 527
2.4.141 DirSelect .................................................................................... 529
2.4.142 Disable ....................................................................................... 530
2.4.143 DisableCommit ........................................................................... 531
2.4.144 DisconnectObject ....................................................................... 532
2.4.145 DisconnectServer ....................................................................... 533
2.4.146 Double ........................................................................................ 534
2.4.147 DoVerb ....................................................................................... 535
2.4.148 Drag ........................................................................................... 536
2.4.149 DraggedObject (obsolete) .......................................................... 538
2.4.150 Draw ........................................................................................... 539
2.4.151 EditLabel .................................................................................... 540
2.4.151.1 Syntax 1: For editing a label in a ListView ....................... 540
2.4.151.2 Syntax 2: For editing a label in a TreeView ..................... 541
2.4.152 Enable ........................................................................................ 542
2.4.153 EnableCommit ........................................................................... 543
2.4.154 EntryList ..................................................................................... 544
2.4.155 EvaluateJavascriptAsync ........................................................... 545
2.4.156 EvaluateJavascriptSync ............................................................. 546
2.4.157 ExecRemote .............................................................................. 548
2.4.157.1 Syntax 1: For sending single commands ......................... 548
2.4.157.2 Syntax 2: For commands over an opened channel ......... 549
2.4.158 Exp ............................................................................................. 551
2.4.159 ExpandAll ................................................................................... 551
2.4.160 ExpandItem ................................................................................ 552
2.4.161 ExportJSON ............................................................................... 553
2.4.162 ExportXML ................................................................................. 554
2.4.163 ExportToJSONFile ..................................................................... 554
2.4.164 ExportToXMLFile ....................................................................... 555
2.4.165 Extract ........................................................................................ 557
2.4.166 Fact ............................................................................................ 560
2.4.167 FileClose .................................................................................... 560
2.4.168 FileCopy ..................................................................................... 561
2.4.169 FileDelete ................................................................................... 562
2.4.170 FileEncoding .............................................................................. 562
2.4.171 FileExists .................................................................................... 564
2.4.172 FileLength .................................................................................. 564
2.4.173 FileLength64 .............................................................................. 566
2.4.174 FileMove .................................................................................... 567
2.4.175 FileOpen .................................................................................... 567
2.4.176 FileRead ..................................................................................... 571
2.4.177 FileReadEx ................................................................................ 573
2.4.178 FileSeek ..................................................................................... 575
2.4.179 FileSeek64 ................................................................................. 576
2.4.180 FileWrite ..................................................................................... 577
2.4.181 FileWriteEx ................................................................................. 579
2.4.182 Fill .............................................................................................. 581
2.4.183 FillA ............................................................................................ 581
2.4.184 FillW (obsolete) .......................................................................... 582
2.4.185 Find ............................................................................................ 582
2.4.186 FindCategory ............................................................................. 584
2.4.187 FindClassDefinition .................................................................... 585
2.4.188 FindFunctionDefinition ............................................................... 586
2.4.189 FindItem ..................................................................................... 587
2.4.189.1 Syntax 1: For ListBox, DropDownListBox, and
RibbonComboBoxItem controls ....................................................... 587
2.4.189.2 Syntax 2: For ListView controls ....................................... 588
2.4.189.3 Syntax 3: For ListView controls ....................................... 589
2.4.189.4 Syntax 4: For TreeView controls ..................................... 591
2.4.190 FindMatchingFunction ................................................................ 593
2.4.191 FindNext ..................................................................................... 594
2.4.192 FindSeries .................................................................................. 595
2.4.193 FindTypeDefinition ..................................................................... 596
2.4.194 FromAnsi .................................................................................... 598
2.4.195 FromUnicode ............................................................................. 599
2.4.196 GarbageCollect .......................................................................... 599
2.4.197 GarbageCollectGetTimeLimit ..................................................... 600
2.4.198 GarbageCollectSetTimeLimit ..................................................... 600
2.4.199 GetAccessToken ........................................................................ 601
2.4.200 GetActiveCategory ..................................................................... 602
2.4.201 GetActiveSheet .......................................................................... 603
2.4.202 GetAlignment ............................................................................. 604
2.4.203 GetApplication ............................................................................ 605
2.4.204 GetApplicationButton ................................................................. 605
2.4.205 GetArgElement .......................................................................... 606
2.4.206 GetAutomationNativePointer ...................................................... 607
2.4.207 GetBestHeight ............................................................................ 608
2.4.208 GetBody ..................................................................................... 609
2.4.208.1 Syntax 1: for TokenResponse objects ............................. 609
2.4.208.2 Syntax 2: for OAuthRequest objects ............................... 610
2.4.208.3 Syntax 3: for ResourceResponse objects ........................ 611
2.4.209 GetBoxPictureList ...................................................................... 612
2.4.210 GetByte ...................................................................................... 613
2.4.211 GetByteArray ............................................................................. 614
2.4.212 GetCategory ............................................................................... 614
2.4.213 GetCategoryByIndex .................................................................. 615
2.4.214 GetCategoryCount ..................................................................... 616
2.4.215 GetCategoryIndex ...................................................................... 617
2.4.216 GetCertificateLabel (obsolete) ................................................... 618
2.4.217 GetCheckBox ............................................................................. 620
2.4.218 GetChildCount ........................................................................... 621
2.4.219 GetChildItem .............................................................................. 623
2.4.220 GetChildItemByIndex ................................................................. 625
2.4.221 GetChildItemCount ..................................................................... 626
2.4.222 GetChildKey ............................................................................... 627
2.4.223 GetChildrenList .......................................................................... 629
2.4.224 GetColumn ................................................................................. 630
2.4.225 GetComboBox ........................................................................... 631
2.4.226 GetCommandDDE ..................................................................... 632
2.4.227 GetCommandDDEOrigin ............................................................ 633
2.4.228 GetCommandString ................................................................... 634
2.4.229 GetCompanyName .................................................................... 635
2.4.230 GetContextKeywords ................................................................. 636
2.4.231 GetContextService ..................................................................... 637
2.4.232 GetCredentialAttribute (obsolete) .............................................. 639
2.4.233 GetCurrentDirectory ................................................................... 641
2.4.234 GetData ...................................................................................... 641
2.4.234.1 Syntax 1: For data points in graphs ................................ 641
2.4.234.2 Syntax 2: For EditMask controls ...................................... 643
2.4.234.3 Syntax 3: For data in an OLE server ............................... 644
2.4.235 GetDataDDE .............................................................................. 646
2.4.236 GetDataDDEOrigin ..................................................................... 646
2.4.237 GetDataLabelling ....................................................................... 647
2.4.238 GetDataPieExplode .................................................................... 649
2.4.239 GetDataStyle .............................................................................. 650
2.4.239.1 Syntax 1: For the colors of a data point .......................... 650
2.4.239.2 Syntax 2: For the line style and width used by a data
point ................................................................................................. 652
2.4.239.3 Syntax 3: For the fill pattern or symbol of a data point ..... 653
2.4.240 GetDataTransparency ................................................................ 655
2.4.241 GetDataValue ............................................................................ 656
2.4.242 GetDateLimits ............................................................................ 658
2.4.243 GetDbmlsyncPath ...................................................................... 659
2.4.244 GetDisplayRange ....................................................................... 660
2.4.245 GetDotNetCoreVersion .............................................................. 661
2.4.246 GetDynamicDate ........................................................................ 662
2.4.247 GetDynamicDateTime ................................................................ 664
2.4.248 GetDynamicDecimal .................................................................. 665
2.4.249 GetDynamicNumber ................................................................... 666
2.4.250 GetDynamicString ...................................................................... 667
2.4.251 GetDynamicTime ....................................................................... 668
2.4.252 GetEnvironment ......................................................................... 669
2.4.253 GetExpiresIn .............................................................................. 670
2.4.254 GetFileOpenName ..................................................................... 671
2.4.255 GetFileSaveName ...................................................................... 675
2.4.256 GetFilesCount ............................................................................ 677
2.4.257 GetFilesList ................................................................................ 678
2.4.258 GetFirstSheet ............................................................................. 679
2.4.259 GetFixesVersion ........................................................................ 680
2.4.260 GetFocus ................................................................................... 681
2.4.261 GetFolder ................................................................................... 682
2.4.262 GetGroup ................................................................................... 683
2.4.263 GetGlobalProperty (obsolete) .................................................... 684
2.4.264 GetHeader ................................................................................. 685
2.4.264.1 Syntax 1: for TokenRequest objects ................................ 685
2.4.264.2 Syntax 2: for TokenResponse objects ............................. 686
2.4.264.3 Syntax 3: for OAuthRequest objects ............................... 687
2.4.264.4 Syntax 4: for ResourceResponse objects ........................ 688
2.4.265 GetHeaders ................................................................................ 689
2.4.265.1 Syntax 1: for TokenRequest objects ................................ 689
2.4.265.2 Syntax 2: for TokenResponse objects ............................. 689
2.4.265.3 Syntax 3: for OAuthRequest objects ............................... 690
2.4.265.4 Syntax 4: for ResourceResponse objects ........................ 691
2.4.266 GetHostObject ........................................................................... 692
2.4.267 GetInstalledRuntimes ................................................................. 693
2.4.268 GetItem ...................................................................................... 693
2.4.268.1 Syntax 1: For ListView controls ....................................... 694
2.4.268.2 Syntax 2: For ListView controls ....................................... 695
2.4.268.3 Syntax 3: For TreeView controls ..................................... 696
2.4.268.4 Syntax 4: For RibbonMenu controls ................................ 697
2.4.268.5 Syntax 5: For RibbonBar controls ................................... 698
2.4.269 GetItemArray .............................................................................. 699
2.4.269.1 Syntax 1 ........................................................................... 699
2.4.269.2 Syntax 2 ........................................................................... 701
2.4.270 GetItemArrayJSONString ........................................................... 703
2.4.270.1 Syntax 1 ........................................................................... 703
2.4.270.2 Syntax 2 ........................................................................... 704
2.4.270.3 Syntax 3 ........................................................................... 705
2.4.271 GetItemAtPointer ....................................................................... 707
2.4.272 GetItemBlob ............................................................................... 707
2.4.272.1 Syntax 1 ........................................................................... 707
2.4.272.2 Syntax 2 ........................................................................... 709
2.4.272.3 Syntax 3 ........................................................................... 710
2.4.273 GetItemBoolean ......................................................................... 711
2.4.273.1 Syntax 1 ........................................................................... 711
2.4.273.2 Syntax 2 ........................................................................... 712
2.4.273.3 Syntax 3 ........................................................................... 714
2.4.274 GetItemByTag ............................................................................ 715
2.4.275 GetItemByPath ........................................................................... 717
2.4.276 GetItemCount ............................................................................. 719
2.4.277 GetItemDate ............................................................................... 720
2.4.277.1 Syntax 1 ........................................................................... 720
2.4.277.2 Syntax 2 ........................................................................... 721
2.4.277.3 Syntax 3 ........................................................................... 722
2.4.278 GetItemDateTime ....................................................................... 724
2.4.278.1 Syntax 1 ........................................................................... 724
2.4.278.2 Syntax 2 ........................................................................... 725
2.4.278.3 Syntax 3 ........................................................................... 726
2.4.279 GetItemNumber ......................................................................... 728
2.4.279.1 Syntax 1 ........................................................................... 728
2.4.279.2 Syntax 2 ........................................................................... 729
2.4.279.3 Syntax 3 ........................................................................... 730
2.4.280 GetItemObject ............................................................................ 731
2.4.280.1 Syntax 1 ........................................................................... 731
2.4.280.2 Syntax 2 ........................................................................... 733
2.4.281 GetItemObjectJSONString ......................................................... 734
2.4.281.1 Syntax 1 ........................................................................... 734
2.4.281.2 Syntax 2 ........................................................................... 736
2.4.281.3 Syntax 3 ........................................................................... 737
2.4.282 GetItemParent ............................................................................ 738
2.4.283 GetItemString ............................................................................. 739
2.4.283.1 Syntax 1 ........................................................................... 739
2.4.283.2 Syntax 2 ........................................................................... 740
2.4.283.3 Syntax 3 ........................................................................... 742
2.4.284 GetItemTime .............................................................................. 743
2.4.284.1 Syntax 1 ........................................................................... 743
2.4.284.2 Syntax 2 ........................................................................... 744
2.4.284.3 Syntax 3 ........................................................................... 745
2.4.285 GetItemType .............................................................................. 747
2.4.286 GetJsonBlob .............................................................................. 752
2.4.287 GetJsonString ............................................................................ 753
2.4.288 GetJWTToken ............................................................................ 754
2.4.289 GetKey ....................................................................................... 756
2.4.290 GetLargeButton .......................................................................... 757
2.4.291 GetLastReturn ............................................................................ 758
2.4.292 GetLibraryList ............................................................................. 759
2.4.293 GetMajorVersion ........................................................................ 760
2.4.294 GetMasterItem ........................................................................... 761
2.4.295 GetMasterItemCount .................................................................. 763
2.4.296 GetMenu .................................................................................... 764
2.4.297 GetMenuByButtonHandle .......................................................... 765
2.4.298 GetMessage ............................................................................... 767
2.4.299 GetMinorVersion ........................................................................ 768
2.4.300 GetName .................................................................................... 769
2.4.301 GetNativePointer ........................................................................ 770
2.4.302 GetNextSheet ............................................................................ 771
2.4.303 GetNumberType ........................................................................ 772
2.4.304 GetOAuthToken ......................................................................... 776
2.4.305 GetObjectRevisionFromRegistry ................................................ 777
2.4.306 GetOrigin .................................................................................... 778
2.4.307 GetPanel .................................................................................... 779
2.4.308 GetParagraphSetting ................................................................. 780
2.4.309 GetParent ................................................................................... 781
2.4.310 GetPathByItem ........................................................................... 782
2.4.311 GetPin (obsolete) ....................................................................... 783
2.4.312 GetRecentItem ........................................................................... 785
2.4.313 GetRecentItemCount ................................................................. 786
2.4.314 GetRecentTitle ........................................................................... 787
2.4.315 GetRecordSet ............................................................................ 789
2.4.316 GetRefreshToken ....................................................................... 790
2.4.317 GetRemote ................................................................................. 791
2.4.317.1 Syntax 1: For single DDE requests ................................. 791
2.4.317.2 Syntax 2: For DDE requests via an open channel ........... 792
2.4.318 GetRequestHeader .................................................................... 794
2.4.319 GetRequestHeaders .................................................................. 794
2.4.320 GetResponseBody ..................................................................... 795
2.4.321 GetResponseHeader ................................................................. 797
2.4.322 GetResponseHeaders ................................................................ 797
2.4.323 GetResponseStatusCode .......................................................... 798
2.4.324 GetResponseStatusText ............................................................ 799
2.4.325 GetRootItem ............................................................................... 800
2.4.326 GetSelectedDate ........................................................................ 801
2.4.327 GetSelectedRange ..................................................................... 802
2.4.328 GetSeriesLabelling ..................................................................... 803
2.4.329 GetSeriesStyle ........................................................................... 804
2.4.329.1 Syntax 1: For the colors of a series ................................ 805
2.4.329.2 Syntax 2: For the line style and width used by a series ... 806
2.4.329.3 Syntax 3: For the fill pattern or symbol of a series ........... 808
2.4.329.4 Syntax 4: For determining whether a series is an
overlay .............................................................................................. 809
2.4.330 GetSeriesTransparency ............................................................. 810
2.4.331 GetShortName ........................................................................... 811
2.4.332 GetSmallButton .......................................................................... 812
2.4.333 GetSource .................................................................................. 813
2.4.334 GetSpacing ................................................................................ 814
2.4.335 GetStatusCode .......................................................................... 815
2.4.335.1 Syntax 1: for TokenResponse objects ............................. 815
2.4.335.2 Syntax 2: for ResourceResponse objects ........................ 816
2.4.336 GetStatusText ............................................................................ 817
2.4.336.1 Syntax 1: for TokenResponse objects ............................. 817
2.4.336.2 Syntax 2: for ResourceResponse objects ........................ 818
2.4.337 GetStatus (obsolete) .................................................................. 818
2.4.338 GetSyncRegistryProperties ........................................................ 820
2.4.339 GetTabButton ............................................................................. 821
2.4.340 GetTabButtonByIndex ................................................................ 822
2.4.341 GetTabButtonCount ................................................................... 823
2.4.342 GetText ...................................................................................... 824
2.4.343 GetTextColor .............................................................................. 825
2.4.344 GetTextStyle .............................................................................. 826
2.4.345 GetTheme .................................................................................. 827
2.4.346 GetToday ................................................................................... 827
2.4.347 GetTokenError ........................................................................... 828
2.4.348 GetTokenType ........................................................................... 829
2.4.349 GetToolbar ................................................................................. 830
2.4.350 GetToolbarPos ........................................................................... 832
2.4.350.1 Syntax 1: For docked toolbars ........................................ 832
2.4.350.2 Syntax 2: For floating toolbars ........................................ 833
2.4.351 GetTransactionName (obsolete) ................................................ 834
2.4.352 GetURL ...................................................................................... 835
2.4.353 GetValue .................................................................................... 837
2.4.353.1 Syntax 1: for DatePicker control ...................................... 837
2.4.353.2 Syntax 2: for JSONPackage object ................................. 838
2.4.354 GetValueBlob ............................................................................. 839
2.4.355 GetValueBoolean ....................................................................... 840
2.4.356 GetValueDate ............................................................................ 841
2.4.357 GetValueDateTime ..................................................................... 842
2.4.358 GetValueNumber ....................................................................... 844
2.4.359 GetValueString ........................................................................... 845
2.4.360 GetValueTime ............................................................................ 846
2.4.361 GetValueToDataWindow ............................................................ 847
2.4.362 GetVersionName ....................................................................... 851
2.4.363 GoBack ...................................................................................... 852
2.4.364 GoForward ................................................................................. 853
2.4.365 Handle ........................................................................................ 854
2.4.366 HexDecode ................................................................................ 855
2.4.367 HexEncode ................................................................................ 856
2.4.368 Hide ............................................................................................ 857
2.4.369 HMAC ........................................................................................ 859
2.4.370 Hour ........................................................................................... 860
2.4.371 HyperLinkToURL ....................................................................... 861
2.4.372 Idle ............................................................................................. 861
2.4.373 ImpersonateClient ...................................................................... 863
2.4.374 ImportClipboard ......................................................................... 864
2.4.375 ImportFile ................................................................................... 866
2.4.375.1 Syntax 1: for Graph controls ........................................... 866
2.4.375.2 Syntax 2: for JSONGenerator objects ............................. 870
2.4.376 ImportString ............................................................................... 872
2.4.376.1 Syntax 1: for Graph controls ........................................... 872
2.4.376.2 Syntax 2: for JSONGenerator objects ............................. 874
2.4.377 ImportJSON ............................................................................... 876
2.4.378 ImportXML ................................................................................. 877
2.4.379 ImportFromJSONFile ................................................................. 878
2.4.380 ImportFromXMLFile ................................................................... 879
2.4.381 IncomingCallList ......................................................................... 880
2.4.382 Init (obsolete) ............................................................................. 882
2.4.383 InputFieldChangeData ............................................................... 884
2.4.384 InputFieldCurrentName .............................................................. 885
2.4.385 InputFieldDeleteCurrent ............................................................. 886
2.4.386 InputFieldGetData ...................................................................... 887
2.4.387 InputFieldInsert .......................................................................... 888
2.4.388 InputFieldLocate ........................................................................ 888
2.4.389 InsertCategory ........................................................................... 890
2.4.389.1 Syntax 1: for Graph controls ........................................... 890
2.4.389.2 Syntax 2: for RibbonBar controls ..................................... 891
2.4.390 InsertCategoryFirst ..................................................................... 893
2.4.391 InsertCategoryLast ..................................................................... 894
2.4.392 InsertCheckBox .......................................................................... 895
2.4.393 InsertCheckBoxFirst ................................................................... 897
2.4.394 InsertCheckBoxLast ................................................................... 898
2.4.395 InsertClass ................................................................................. 900
2.4.396 InsertColumn .............................................................................. 901
2.4.397 InsertComboBox ........................................................................ 901
2.4.398 InsertComboBoxFirst ................................................................. 904
2.4.399 InsertComboBoxLast .................................................................. 905
2.4.400 InsertData .................................................................................. 907
2.4.401 InsertDocument .......................................................................... 909
2.4.402 InsertFile .................................................................................... 911
2.4.403 InsertGroup ................................................................................ 912
2.4.404 InsertGroupFirst ......................................................................... 913
2.4.405 InsertGroupLast ......................................................................... 914
2.4.406 InsertItem ................................................................................... 915
2.4.406.1 Syntax 1: For ListBox and DropDownListBox controls ..... 915
2.4.406.2 Syntax 2: For PictureListBox, DropDownPictureListBox,
RibbonComboBoxItem controls ....................................................... 917
2.4.406.3 Syntax 3: For ListView controls ....................................... 918
2.4.406.4 Syntax 4: For ListView controls ....................................... 919
2.4.406.5 Syntax 5: For TreeView controls ..................................... 919
2.4.406.6 Syntax 6: For TreeView controls ..................................... 920
2.4.406.7 Syntax 7: For RibbonMenu controls ................................ 921
2.4.407 InsertItemFirst ............................................................................ 923
2.4.407.1 Syntax 1: For TreeView controls ..................................... 923
2.4.407.2 Syntax 2: For TreeView controls ..................................... 924
2.4.407.3 Syntax 3: For RibbonMenu controls ................................ 925
2.4.408 InsertItemLast ............................................................................ 927
2.4.408.1 Syntax 1: For TreeView controls ..................................... 928
2.4.408.2 Syntax 2: For TreeView controls ..................................... 929
2.4.408.3 Syntax 3: For RibbonMenu controls ................................ 930
2.4.409 InsertItemSort ............................................................................ 932
2.4.409.1 Syntax 1: For TreeView controls ..................................... 932
2.4.409.2 Syntax 2: For TreeView controls ..................................... 933
2.4.410 InsertLargeButton ...................................................................... 934
2.4.411 InsertLargeButtonFirst ................................................................ 936
2.4.412 InsertLargeButtonLast ................................................................ 937
2.4.413 InsertMasterItem ........................................................................ 939
2.4.414 InsertMasterItemFirst ................................................................. 941
2.4.415 InsertMasterItemLast ................................................................. 944
2.4.416 InsertObject ................................................................................ 946
2.4.417 InsertPanel ................................................................................. 946
2.4.418 InsertPanelFirst .......................................................................... 948
2.4.419 InsertPanelLast .......................................................................... 949
2.4.420 InsertPicture ............................................................................... 950
2.4.421 InsertRecentItem ........................................................................ 951
2.4.422 InsertRecentItemFirst ................................................................. 953
2.4.423 InsertRecentItemLast ................................................................. 954
2.4.424 InsertSeries ................................................................................ 956
2.4.425 InsertSmallButton ....................................................................... 957
2.4.426 InsertSmallButtonFirst ................................................................ 959
2.4.427 InsertSmallButtonLast ................................................................ 961
2.4.428 InsertTabButton ......................................................................... 962
2.4.429 InsertTabButtonFirst ................................................................... 964
2.4.430 InsertTabButtonLast ................................................................... 966
2.4.431 Int ............................................................................................... 967
2.4.432 Integer ........................................................................................ 968
2.4.433 InternetData ............................................................................... 969
2.4.434 IntHigh ........................................................................................ 970
2.4.435 IntLow ........................................................................................ 971
2.4.436 InvokePBFunction ...................................................................... 971
2.4.437 _Is_A (obsolete) ......................................................................... 973
2.4.438 IsAlive ........................................................................................ 974
2.4.439 IsAllArabic .................................................................................. 975
2.4.440 IsAllHebrew ................................................................................ 976
2.4.441 IsAnyArabic ................................................................................ 976
2.4.442 IsAnyHebrew .............................................................................. 977
2.4.443 IsArabic ...................................................................................... 978
2.4.444 IsArabicAndNumbers ................................................................. 979
2.4.445 IsCallerInRole ............................................................................ 979
2.4.446 IsDate ......................................................................................... 981
2.4.447 IsHebrew .................................................................................... 982
2.4.448 IsHebrewAndNumbers ............................................................... 983
2.4.449 IsImpersonating ......................................................................... 983
2.4.450 IsInTransaction (obsolete) ......................................................... 984
2.4.451 IsMinimized ................................................................................ 986
2.4.452 IsNull .......................................................................................... 986
2.4.453 IsNumber ................................................................................... 987
2.4.454 IsPBApp ..................................................................................... 988
2.4.455 IsPowerClientApp ...................................................................... 989
2.4.456 IsPreview ................................................................................... 989
2.4.457 IsSecurityEnabled ...................................................................... 990
2.4.458 IsTime ........................................................................................ 991
2.4.459 IsTransactionAborted (obsolete) ................................................ 992
2.4.460 IsValid ........................................................................................ 993
2.4.461 KeyCount ................................................................................... 994
2.4.462 KeyDown .................................................................................... 995
2.4.463 LastPos ...................................................................................... 998
2.4.464 Left ............................................................................................. 999
2.4.465 LeftA ......................................................................................... 1000
2.4.466 LeftW (obsolete) ...................................................................... 1001
2.4.467 LeftTrim .................................................................................... 1001
2.4.468 LeftTrimW (obsolete) ............................................................... 1002
2.4.469 Len ........................................................................................... 1003
2.4.470 LenA ......................................................................................... 1004
2.4.471 LenW (obsolete) ...................................................................... 1005
2.4.472 Length ...................................................................................... 1005
2.4.473 LibraryCreate ........................................................................... 1006
2.4.474 LibraryDelete ............................................................................ 1007
2.4.475 LibraryDirectory ........................................................................ 1008
2.4.476 LibraryDirectoryEx .................................................................... 1009
2.4.477 LibraryExport ............................................................................ 1011
2.4.478 LibraryImport ............................................................................ 1012
2.4.479 LineCount ................................................................................. 1014
2.4.480 LineLength ............................................................................... 1015
2.4.481 LineList ..................................................................................... 1016
2.4.482 LinkTo ...................................................................................... 1017
2.4.483 LoadDockingState .................................................................... 1018
2.4.484 LoadFile ................................................................................... 1018
2.4.485 LoadString ................................................................................ 1020
2.4.486 LoadInk .................................................................................... 1022
2.4.487 LoadPicture .............................................................................. 1023
2.4.488 LoadWithDotNetCore ............................................................... 1024
2.4.489 LoadWithDotNetFramework ..................................................... 1025
2.4.490 Log ........................................................................................... 1027
2.4.490.1 Syntax 1: For all objects ................................................ 1028
2.4.490.2 Syntax 2: For ErrorLogging objects ............................... 1029
2.4.491 LogTen ..................................................................................... 1029
2.4.492 Long ......................................................................................... 1030
2.4.492.1 Syntax 1: For combining integers .................................. 1030
2.4.492.2 Syntax 2: For converting strings and blobs ................... 1031
2.4.493 LongLong ................................................................................. 1032
2.4.493.1 Syntax 1: For combining longs ...................................... 1032
2.4.493.2 Syntax 2: For converting strings and blobs ................... 1033
2.4.494 Lookup (obsolete) .................................................................... 1034
2.4.494.1 Syntax 1: For CORBA-compliant EAServer
components .................................................................................... 1034
2.4.494.2 Syntax 2: For instances of an EJB component .............. 1035
2.4.495 Lower ....................................................................................... 1038
2.4.496 LowerBound ............................................................................. 1039
2.4.497 mailAddress ............................................................................. 1040
2.4.498 mailDeleteMessage .................................................................. 1041
2.4.499 mailGetMessages .................................................................... 1042
2.4.500 mailHandle ............................................................................... 1044
2.4.501 mailLogoff ................................................................................ 1044
2.4.502 mailLogon ................................................................................ 1045
2.4.503 mailReadMessage ................................................................... 1047
2.4.504 mailRecipientDetails ................................................................. 1049
2.4.505 mailResolveRecipient ............................................................... 1050
2.4.506 mailSaveMessage .................................................................... 1052
2.4.507 mailSend .................................................................................. 1054
2.4.508 Match ....................................................................................... 1056
2.4.509 MatchW (obsolete) ................................................................... 1058
2.4.510 Max .......................................................................................... 1059
2.4.511 MD5 ......................................................................................... 1059
2.4.512 MemberDelete ......................................................................... 1061
2.4.513 MemberExists .......................................................................... 1062
2.4.514 MemberRename ...................................................................... 1063
2.4.515 MessageBox ............................................................................ 1064
2.4.516 Mid ........................................................................................... 1066
2.4.517 MidA ......................................................................................... 1068
2.4.518 MidW (obsolete) ....................................................................... 1068
2.4.519 Min ........................................................................................... 1068
2.4.520 Minute ...................................................................................... 1069
2.4.521 Mod .......................................................................................... 1070
2.4.522 ModifyData ............................................................................... 1070
2.4.522.1 Syntax 1: For all graph types except scatter ................. 1071
2.4.522.2 Syntax 2: For scatter graphs ......................................... 1072
2.4.523 Month ....................................................................................... 1073
2.4.524 Move ........................................................................................ 1073
2.4.525 MoveTab .................................................................................. 1075
2.4.526 _Narrow (obsolete) .................................................................. 1075
2.4.527 Navigate ................................................................................... 1077
2.4.528 NextActivity .............................................................................. 1078
2.4.529 Now .......................................................................................... 1079
2.4.530 ObjectAtPointer ........................................................................ 1080
2.4.531 OffsetPos ................................................................................. 1082
2.4.532 Open ........................................................................................ 1082
2.4.532.1 Syntax 1: For windows of a known datatype ................. 1083
2.4.532.2 Syntax 2: For windows of unknown datatype ................ 1085
2.4.532.3 Syntax 3: For loading an OLE object from a file into a
control ............................................................................................ 1087
2.4.532.4 Syntax 4: For opening an OLE object in memory into a
control ............................................................................................ 1088
2.4.532.5 Syntax 5: For opening an OLE object in a file into an
OLEStorage ................................................................................... 1089
2.4.532.6 Syntax 6: For opening an OLE storage member into a
storage ........................................................................................... 1091
2.4.532.7 Syntax 7: For opening OLE streams ............................. 1093
2.4.532.8 Syntax 8: For opening trace files ................................... 1095
2.4.533 OpenChannel ........................................................................... 1096
2.4.534 OpenSheet ............................................................................... 1098
2.4.535 OpenSheetAsDocument .......................................................... 1100
2.4.536 OpenSheetDocked ................................................................... 1101
2.4.537 OpenSheetFromDockingState ................................................. 1102
2.4.538 OpenSheetInTabGroup ............................................................ 1103
2.4.539 OpenSheetWithParm ............................................................... 1103
2.4.540 OpenSheetWithParmAsDocument ........................................... 1106
2.4.541 OpenSheetWithParmDocked ................................................... 1108
2.4.542 OpenSheetWithParmFromDockingState ................................. 1109
2.4.543 OpenSheetWithParmInTabGroup ............................................ 1111
2.4.544 OpenTab .................................................................................. 1112
2.4.544.1 Syntax 1: For user objects of a known datatype ............ 1112
2.4.544.2 Syntax 2: For user objects of unknown datatype ........... 1114
2.4.545 OpenTabWithParm .................................................................. 1116
2.4.545.1 Syntax 1: For user objects of a known datatype ............ 1116
2.4.545.2 Syntax 2: For user objects of unknown datatype ........... 1118
2.4.546 OpenUserObject ...................................................................... 1120
2.4.546.1 Syntax 1: For user objects of a known datatype ............ 1120
2.4.546.2 Syntax 2: For user objects of unknown datatype ........... 1121
2.4.547 OpenUserObjectWithParm ....................................................... 1123
2.4.547.1 Syntax 1: For user objects of a known datatype ............ 1123
2.4.547.2 Syntax 2: For user objects of unknown datatype ........... 1125
2.4.548 OpenWithParm ........................................................................ 1127
2.4.548.1 Syntax 1: For windows of a known datatype ................. 1127
2.4.548.2 Syntax 2: For windows of unknown datatype ................ 1129
2.4.549 OutgoingCallList ....................................................................... 1131
2.4.550 PageCount ............................................................................... 1133
2.4.551 PageCreated ............................................................................ 1133
2.4.552 ParentWindow .......................................................................... 1134
2.4.553 Paste ........................................................................................ 1135
2.4.554 PasteLink ................................................................................. 1137
2.4.555 PasteRTF ................................................................................. 1138
2.4.556 PasteSpecial ............................................................................ 1139
2.4.557 PauseDownload ....................................................................... 1140
2.4.558 PBAddCookie (Obsolete) ......................................................... 1141
2.4.559 PBGetCookies (Obsolete) ........................................................ 1142
2.4.560 PBGetMenuString .................................................................... 1142
2.4.561 Pi .............................................................................................. 1143
2.4.562 PixelsToUnits ........................................................................... 1144
2.4.563 Play .......................................................................................... 1145
2.4.564 PointerX ................................................................................... 1146
2.4.565 PointerY ................................................................................... 1147
2.4.566 PopMenu .................................................................................. 1148
2.4.567 PopulateError ........................................................................... 1149
2.4.568 Pos ........................................................................................... 1150
2.4.569 PosA ........................................................................................ 1151
2.4.570 PosW (obsolete) ...................................................................... 1152
2.4.571 Position .................................................................................... 1152
2.4.571.1 Syntax 1: For editable controls, except RichTextEdit ..... 1152
2.4.571.2 Syntax 2: For RichTextEdit controls .............................. 1153
2.4.572 Post .......................................................................................... 1157
2.4.573 PostData .................................................................................. 1158
2.4.574 PostDataEnd ............................................................................ 1159
2.4.575 PostDataStart ........................................................................... 1160
2.4.576 PostEvent ................................................................................. 1161
2.4.577 PostURL ................................................................................... 1164
2.4.578 Preview .................................................................................... 1166
2.4.579 Print .......................................................................................... 1167
2.4.579.1 Syntax 1: For printing a visual object in a print job ........ 1167
2.4.579.2 Syntax 2: For printing text in a print job ......................... 1169
2.4.579.3 Syntax 3: For RichTextEdit controls .............................. 1172
2.4.580 PrintAsPDF .............................................................................. 1173
2.4.581 PrintBitmap .............................................................................. 1174
2.4.582 PrintCancel .............................................................................. 1175
2.4.583 PrintClose ................................................................................ 1176
2.4.584 PrintDataWindow ..................................................................... 1177
2.4.585 PrintDefineFont ........................................................................ 1178
2.4.586 PrintEx ..................................................................................... 1180
2.4.587 PrintGetPrinter ......................................................................... 1181
2.4.588 PrintGetPrinters ....................................................................... 1181
2.4.589 PrintLine ................................................................................... 1182
2.4.590 PrintOpen ................................................................................. 1183
2.4.591 PrintOval .................................................................................. 1185
2.4.592 PrintPage ................................................................................. 1186
2.4.593 PrintRect .................................................................................. 1187
2.4.594 PrintRoundRect ........................................................................ 1188
2.4.595 PrintScreen .............................................................................. 1190
2.4.596 PrintSend (obsolete) ................................................................ 1190
2.4.597 PrintSetFont ............................................................................. 1192
2.4.598 PrintSetPrinter .......................................................................... 1193
2.4.599 PrintSetSpacing ....................................................................... 1194
2.4.600 PrintSetup ................................................................................ 1194
2.4.601 PrintSetupPrinter ...................................................................... 1195
2.4.602 PrintText ................................................................................... 1196
2.4.603 PrintWidth ................................................................................ 1197
2.4.604 PrintX ....................................................................................... 1198
2.4.605 PrintY ....................................................................................... 1199
2.4.606 ProfileInt ................................................................................... 1199
2.4.607 ProfileString ............................................................................. 1201
2.4.608 Rand ........................................................................................ 1202
2.4.609 Randomize ............................................................................... 1203
2.4.610 Read ........................................................................................ 1204
2.4.610.1 Syntax 1: For reading into a string ................................ 1204
2.4.610.2 Syntax 2: For character arrays or blobs ........................ 1205
2.4.611 ReadData ................................................................................. 1206
2.4.612 Real .......................................................................................... 1208
2.4.613 RecognizeText ......................................................................... 1209
2.4.614 Refresh .................................................................................... 1210
2.4.615 RegisterEvent .......................................................................... 1211
2.4.616 RegistryDelete ......................................................................... 1212
2.4.617 RegistryGet .............................................................................. 1213
2.4.618 RegistryKeys ............................................................................ 1215
2.4.619 RegistrySet .............................................................................. 1216
2.4.620 RegistryValues ......................................................................... 1218
2.4.621 RelativeDate ............................................................................ 1219
2.4.622 RelativeTime ............................................................................ 1219
2.4.623 ReleaseAutomationNativePointer ............................................ 1220
2.4.624 ReleaseNativePointer .............................................................. 1221
2.4.625 Remove .................................................................................... 1222
2.4.626 RemoveApplicationButton ........................................................ 1223
2.4.627 RemoveDirectory ..................................................................... 1223
2.4.628 RequestResource .................................................................... 1224
2.4.629 Repair ...................................................................................... 1225
2.4.630 Replace .................................................................................... 1226
2.4.631 ReplaceA ................................................................................. 1228
2.4.632 ReplaceText ............................................................................. 1229
2.4.633 ReplaceW (obsolete) ............................................................... 1230
2.4.634 Reset ........................................................................................ 1230
2.4.634.1 Syntax 1: For list boxes ................................................. 1230
2.4.634.2 Syntax 2: For graphs ..................................................... 1231
2.4.634.3 Syntax 3: For trace files ................................................ 1232
2.4.635 ResetArgElements ................................................................... 1233
2.4.636 ResetDataColors ...................................................................... 1234
2.4.637 ResetInk ................................................................................... 1235
2.4.638 ResetPicture ............................................................................ 1235
2.4.639 Resize ...................................................................................... 1236
2.4.640 RespondRemote ...................................................................... 1237
2.4.641 Restart ..................................................................................... 1238
2.4.642 ResumeDownload .................................................................... 1239
2.4.643 ResumeTransaction (obsolete) ................................................ 1240
2.4.644 Retrieve .................................................................................... 1241
2.4.645 RetrieveOne ............................................................................. 1248
2.4.646 Reverse .................................................................................... 1250
2.4.647 RevertToSelf ............................................................................ 1251
2.4.648 RGB ......................................................................................... 1252
2.4.649 Right ......................................................................................... 1253
2.4.650 RightA ...................................................................................... 1254
2.4.651 RightW (obsolete) .................................................................... 1255
2.4.652 RightTrim ................................................................................. 1255
2.4.653 RightTrimW (obsolete) ............................................................. 1256
2.4.654 RollbackOnly (obsolete) ........................................................... 1256
2.4.655 RollbackTransaction (obsolete) ............................................... 1257
2.4.656 Round ...................................................................................... 1259
2.4.657 RoutineList ............................................................................... 1260
2.4.658 Run .......................................................................................... 1261
2.4.659 Save ......................................................................................... 1262
2.4.659.1 Syntax 1: For InkPicture controls .................................. 1262
2.4.659.2 Syntax 2: For OLE objects ............................................ 1264
2.4.660 SaveAs ..................................................................................... 1265
2.4.660.1 Syntax 1: For graph objects .......................................... 1266
2.4.660.2 Syntax 2: For saving an OLE control to a file ................ 1268
2.4.660.3 Syntax 3: For saving an OLE control to an OLE
storage ........................................................................................... 1269
2.4.660.4 Syntax 4: For saving an OLE storage object to a file ..... 1270
2.4.660.5 Syntax 5: For saving an OLE storage object in another
OLE storage ................................................................................... 1272
2.4.661 SaveDockingState .................................................................... 1273
2.4.662 SaveDocument ........................................................................ 1273
2.4.663 SaveInk .................................................................................... 1275
2.4.664 SaveToFile ............................................................................... 1277
2.4.665 Scroll ........................................................................................ 1278
2.4.666 ScrollNextPage ........................................................................ 1279
2.4.667 ScrollNextRow ......................................................................... 1280
2.4.668 ScrollPriorPage ........................................................................ 1281
2.4.669 ScrollPriorRow ......................................................................... 1282
2.4.670 ScrollToRow ............................................................................. 1283
2.4.671 Second ..................................................................................... 1284
2.4.672 SecondsAfter ........................................................................... 1285
2.4.673 Seek ......................................................................................... 1286
2.4.673.1 Syntax 1: For OLE stream objects ................................ 1286
2.4.673.2 Syntax 2: For animation controls ................................... 1287
2.4.674 SelectedColumn ....................................................................... 1288
2.4.675 SelectedIndex .......................................................................... 1289
2.4.676 SelectedItem ............................................................................ 1290
2.4.677 SelectedLength ........................................................................ 1291
2.4.678 SelectedLine ............................................................................ 1292
2.4.679 SelectedPage ........................................................................... 1293
2.4.680 SelectedStart ........................................................................... 1294
2.4.681 SelectedText ............................................................................ 1295
2.4.682 SelectionRange ........................................................................ 1296
2.4.683 SelectItem ................................................................................ 1297
2.4.683.1 Syntax 1: When you know the text of an item ............... 1298
2.4.683.2 Syntax 2: When you know the item number .................. 1299
2.4.683.3 Syntax 3: For TreeView controls ................................... 1300
2.4.684 SelectObject ............................................................................. 1301
2.4.685 SelectTab ................................................................................. 1302
2.4.686 SelectText ................................................................................ 1303
2.4.686.1 Syntax 1: For editable controls (except RichTextEdit) ... 1303
2.4.686.2 Syntax 2: For RichTextEdit controls and presentation
styles .............................................................................................. 1304
2.4.687 SelectTextAll ............................................................................ 1306
2.4.688 SelectTextLine ......................................................................... 1307
2.4.689 SelectTextWord ....................................................................... 1308
2.4.690 Send ......................................................................................... 1310
2.4.691 SendDeleteRequest ................................................................. 1312
2.4.692 SendGetRequest ..................................................................... 1313
2.4.693 SendPatchRequest .................................................................. 1315
2.4.694 SendPostRequest .................................................................... 1317
2.4.695 SendPutRequest ...................................................................... 1319
2.4.696 SendRequest ........................................................................... 1321
2.4.697 SeriesCount ............................................................................. 1324
2.4.698 SeriesName ............................................................................. 1325
2.4.699 SetAbort ................................................................................... 1326
2.4.699.1 Syntax 1: For OLETxnObject objects ............................ 1326
2.4.699.2 Syntax 2: For TransactionServer objects ....................... 1327
2.4.700 SetAccessToken ...................................................................... 1328
2.4.701 SetActiveCategory ................................................................... 1329
2.4.702 SetActiveCategoryByIndex ...................................................... 1330
2.4.703 SetAlignment ............................................................................ 1331
2.4.704 SetApplicationButton ................................................................ 1332
2.4.705 SetArgElement ......................................................................... 1333
2.4.706 SetAutomationLocale ............................................................... 1334
2.4.707 SetAutomationPointer .............................................................. 1335
2.4.708 SetAutomationTimeout ............................................................. 1336
2.4.709 SetBody ................................................................................... 1338
2.4.710 SetBoldDate ............................................................................. 1339
2.4.711 SetBoxPictureList ..................................................................... 1340
2.4.712 SetByte .................................................................................... 1341
2.4.713 SetCategory ............................................................................. 1342
2.4.714 SetCheckBox ........................................................................... 1343
2.4.715 SetColumn ............................................................................... 1344
2.4.716 SetComboBox .......................................................................... 1345
2.4.717 SetComplete ............................................................................ 1346
2.4.717.1 Syntax 1: For OLETxnObject objects ............................ 1347
2.4.717.2 Syntax 2: For TransactionServer objects ....................... 1347
2.4.718 SetData .................................................................................... 1349
2.4.719 SetDataDDE ............................................................................ 1350
2.4.720 SetDataLabelling ...................................................................... 1352
2.4.721 SetDataPieExplode .................................................................. 1353
2.4.722 SetDataStyle ............................................................................ 1354
2.4.722.1 Syntax 1: For setting a data point's colors ..................... 1354
2.4.722.2 Syntax 2: For the line associated with a data point ........ 1356
2.4.722.3 Syntax 3: For the fill pattern and symbol of a data
point ............................................................................................... 1358
2.4.723 SetDataTransparency .............................................................. 1360
2.4.724 SetDateLimits ........................................................................... 1361
2.4.725 SetDropHighlight ...................................................................... 1362
2.4.726 SetDynamicParm ..................................................................... 1363
2.4.727 SetFirstVisible .......................................................................... 1364
2.4.728 SetFocus .................................................................................. 1365
2.4.729 SetGroup .................................................................................. 1365
2.4.730 SetGlobalProperty (obsolete) ................................................... 1366
2.4.731 SetHeader ................................................................................ 1368
2.4.731.1 Syntax 1: for TokenRequest objects .............................. 1368
2.4.731.2 Syntax 2: for OAuthRequest objects ............................. 1369
2.4.732 SetHeaders .............................................................................. 1370
2.4.732.1 Syntax 1: for TokenRequest objects .............................. 1370
2.4.732.2 Syntax 2: for OAuthRequest objects ............................. 1370
2.4.733 SetItem ..................................................................................... 1371
2.4.733.1 Syntax 1: For ListView controls ..................................... 1372
2.4.733.2 Syntax 2: For ListView controls ..................................... 1373
2.4.733.3 Syntax 3: For TreeView controls ................................... 1374
2.4.733.4 Syntax 4: For RibbonMenu controls .............................. 1375
2.4.733.5 Syntax 5: For RibbonBar controls ................................. 1376
2.4.734 SetJWTToken .......................................................................... 1378
2.4.735 SetLargeButton ........................................................................ 1380
2.4.736 SetLevelPictures ...................................................................... 1381
2.4.737 SetLibraryList ........................................................................... 1382
2.4.738 SetMask ................................................................................... 1383
2.4.739 SetMasterItem .......................................................................... 1385
2.4.740 SetMenu ................................................................................... 1386
2.4.741 SetMessage ............................................................................. 1388
2.4.742 SetMicroHelp ........................................................................... 1389
2.4.743 SetMinimized ........................................................................... 1390
2.4.744 SetNewMobiLinkPassword ...................................................... 1390
2.4.745 SetNull ..................................................................................... 1391
2.4.746 SetOAuthToken ....................................................................... 1392
2.4.747 SetOverlayPicture .................................................................... 1393
2.4.748 SetPanel .................................................................................. 1395
2.4.749 SetParagraphSetting ................................................................ 1396
2.4.750 SetParm ................................................................................... 1397
2.4.751 SetPicture ................................................................................ 1398
2.4.752 SetPointer ................................................................................ 1399
2.4.752.1 Syntax 1: System-defined shape ................................... 1399
2.4.752.2 Syntax 2: File-defined shape ......................................... 1400
2.4.753 SetPosition ............................................................................... 1401
2.4.753.1 Syntax 1: For positioning windows and controls in
windows ......................................................................................... 1401
2.4.753.2 Syntax 2: For positioning objects within a DataWindow . 1402
2.4.754 SetProfileString ........................................................................ 1403
2.4.755 SetRange ................................................................................. 1405
2.4.756 SetRecentItem ......................................................................... 1406
2.4.757 SetRecentTitle ......................................................................... 1407
2.4.758 SetRecordSet ........................................................................... 1408
2.4.759 SetRedraw ............................................................................... 1410
2.4.760 SetRemote ............................................................................... 1410
2.4.760.1 Syntax 1: For single DDE requests ............................... 1411
2.4.760.2 Syntax 2: For DDE requests via an open channel ......... 1412
2.4.761 SetRequestHeader ................................................................... 1413
2.4.762 SetRequestHeaders ................................................................. 1414
2.4.763 SetResultSet ............................................................................ 1415
2.4.764 SetSelectedDate ...................................................................... 1416
2.4.765 SetSelectedRange ................................................................... 1416
2.4.766 SetSeriesLabelling ................................................................... 1418
2.4.767 SetSeriesStyle ......................................................................... 1419
2.4.767.1 Syntax 1: For setting a series' colors ............................ 1419
2.4.767.2 Syntax 2: For lines in a graph ....................................... 1421
2.4.767.3 Syntax 3: For the fill pattern and symbols in a graph ..... 1422
2.4.767.4 Syntax 4: For creating an overlay in a graph ................. 1424
2.4.768 SetSeriesTransparency ............................................................ 1426
2.4.769 SetSheetID ............................................................................... 1427
2.4.770 SetSmallButton ........................................................................ 1428
2.4.771 SetSpacing ............................................................................... 1429
2.4.772 SetState ................................................................................... 1430
2.4.773 SetSyncRegistryProperties ...................................................... 1431
2.4.774 SetTabButton ........................................................................... 1432
2.4.775 SetTextColor ............................................................................ 1433
2.4.776 SetTextStyle ............................................................................. 1434
2.4.777 SetTimeout (obsolete) ............................................................. 1435
2.4.778 SetToday .................................................................................. 1437
2.4.779 SetToolbar ............................................................................... 1438
2.4.780 SetToolbarPos ......................................................................... 1439
2.4.780.1 Syntax 1: For docked toolbars ....................................... 1439
2.4.780.2 Syntax 2: For floating toolbars ....................................... 1441
2.4.781 SetTop ..................................................................................... 1443
2.4.782 SetTraceFileName ................................................................... 1444
2.4.783 SetTransPool ........................................................................... 1445
2.4.784 SetValue .................................................................................. 1445
2.4.784.1 Syntax 1: for DatePicker control .................................... 1445
2.4.784.2 Syntax 2: for JSONPackage object ............................... 1446
2.4.785 SetValueBlob ........................................................................... 1448
2.4.786 SetValueBoolean ..................................................................... 1449
2.4.787 SetValueByDataWindow .......................................................... 1451
2.4.788 SetValueDate ........................................................................... 1454
2.4.789 SetValueDateTime ................................................................... 1455
2.4.790 SetValueNumber ...................................................................... 1457
2.4.791 SetValueString ......................................................................... 1458
2.4.792 SetValueTime .......................................................................... 1459
2.4.793 SHA .......................................................................................... 1460
2.4.794 SharedObjectDirectory ............................................................. 1462
2.4.795 SharedObjectGet ..................................................................... 1463
2.4.796 SharedObjectRegister .............................................................. 1465
2.4.797 SharedObjectUnregister ........................................................... 1466
2.4.798 Show ........................................................................................ 1467
2.4.799 ShowHeadFoot ........................................................................ 1468
2.4.800 ShowHelp ................................................................................. 1469
2.4.801 ShowPopupHelp ...................................................................... 1470
2.4.802 Sign .......................................................................................... 1471
2.4.803 SignalError ............................................................................... 1472
2.4.804 Sin ............................................................................................ 1473
2.4.805 Sleep ........................................................................................ 1473
2.4.806 Sort .......................................................................................... 1474
2.4.806.1 Syntax 1: For TreeView controls ................................... 1474
2.4.806.2 Syntax 2: For ListView controls ..................................... 1475
2.4.807 SortAll ...................................................................................... 1476
2.4.808 Space ....................................................................................... 1477
2.4.809 Sqrt .......................................................................................... 1478
2.4.810 Start ......................................................................................... 1478
2.4.810.1 Syntax 1: For executing pipeline objects ....................... 1478
2.4.810.2 Syntax 2: For activating timing objects .......................... 1481
2.4.811 StartHotLink ............................................................................. 1485
2.4.812 StartServerDDE ....................................................................... 1486
2.4.813 State ......................................................................................... 1487
2.4.814 StepIt ........................................................................................ 1488
2.4.815 Stop .......................................................................................... 1489
2.4.815.1 Syntax 1: For deactivating timing objects ...................... 1489
2.4.815.2 Syntax 2: For stopping an animation from playing ......... 1490
2.4.816 StopHotLink ............................................................................. 1491
2.4.817 StopNavigation ......................................................................... 1492
2.4.818 StopServerDDE ....................................................................... 1492
2.4.819 String ........................................................................................ 1493
2.4.819.1 Syntax 1: For formatting data ........................................ 1493
2.4.819.2 Syntax 2: For blobs ....................................................... 1497
2.4.820 Submit ...................................................................................... 1498
2.4.821 SuspendTransaction (obsolete) ............................................... 1504
2.4.822 SymmetricDecrypt .................................................................... 1505
2.4.823 SymmetricEncrypt .................................................................... 1507
2.4.824 SymmetricGenerateKey ........................................................... 1510
2.4.825 Synchronize ............................................................................. 1512
2.4.825.1 Syntax 1: For synchronization without parameters ........ 1512
2.4.825.2 Syntax 2: For synchronization with parameters ............. 1512
2.4.826 SyntaxFromSQL ...................................................................... 1513
2.4.827 SystemRoutine ......................................................................... 1516
2.4.828 TabPostEvent .......................................................................... 1517
2.4.829 TabTriggerEvent ...................................................................... 1518
2.4.830 Tan ........................................................................................... 1519
2.4.831 Text .......................................................................................... 1520
2.4.831.1 Syntax for ListBox, DropDownListBox, PictureListBox,
and DropDownPictureListBox controls .......................................... 1520
2.4.831.2 Syntax for RibbonComboBoxItem controls .................... 1521
2.4.832 TextLine ................................................................................... 1521
2.4.833 Time ......................................................................................... 1522
2.4.833.1 Syntax 1: For DateTime and blob values ...................... 1522
2.4.833.2 Syntax 2: For strings ..................................................... 1523
2.4.833.3 Syntax 3: For integers ................................................... 1524
2.4.834 Timer ........................................................................................ 1525
2.4.835 ToAnsi ...................................................................................... 1526
2.4.836 Today ....................................................................................... 1527
2.4.837 Top ........................................................................................... 1527
2.4.838 TotalColumns ........................................................................... 1528
2.4.839 TotalItems ................................................................................ 1529
2.4.840 TotalSelected ........................................................................... 1530
2.4.841 ToUnicode ................................................................................ 1531
2.4.842 TraceBegin ............................................................................... 1532
2.4.843 TraceClose ............................................................................... 1533
2.4.844 TraceDisableActivity ................................................................. 1534
2.4.845 TraceEnableActivity ................................................................. 1535
2.4.846 TraceEnd ................................................................................. 1537
2.4.847 TraceError ................................................................................ 1538
2.4.848 TraceOpen ............................................................................... 1539
2.4.849 TraceUser ................................................................................ 1541
2.4.850 TriggerEvent ............................................................................ 1541
2.4.851 TriggerPBEvent ........................................................................ 1543
2.4.852 Trim .......................................................................................... 1545
2.4.853 TrimW (obsolete) ..................................................................... 1546
2.4.854 Truncate ................................................................................... 1546
2.4.855 TrustVerify (obsolete) .............................................................. 1547
2.4.856 TypeOf ..................................................................................... 1550
2.4.857 Uncheck ................................................................................... 1551
2.4.858 Undo ........................................................................................ 1553
2.4.859 UnitsToPixels ........................................................................... 1553
2.4.860 UnregisterEvent ....................................................................... 1554
2.4.861 UpdateLinksDialog ................................................................... 1555
2.4.862 Upper ....................................................................................... 1557
2.4.863 UpperBound ............................................................................. 1557
2.4.864 UrlDecode ................................................................................ 1559
2.4.865 UrlEncode ................................................................................ 1560
2.4.866 WebBrowserGet ....................................................................... 1561
2.4.867 WebBrowserSet ....................................................................... 1562
2.4.868 Which ....................................................................................... 1564
2.4.869 WordCap .................................................................................. 1565
2.4.870 WorkSpaceHeight .................................................................... 1566
2.4.871 WorkSpaceWidth ..................................................................... 1567
2.4.872 WorkSpaceX ............................................................................ 1568
2.4.873 WorkSpaceY ............................................................................ 1569
2.4.874 Write ......................................................................................... 1570
2.4.875 XMLParseFile .......................................................................... 1571
2.4.876 XMLParseString ....................................................................... 1573
2.4.877 Year ......................................................................................... 1576
2.4.878 Yield ......................................................................................... 1577
2.4.879 Zoom ........................................................................................ 1578
Index .................................................................................................................... 1580
PowerScript Topics

1 PowerScript Topics
This part describes the basics of using the PowerScript language.

1.1 Language Basics


About this chapter
This chapter describes general elements and conventions of PowerScript.

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.

Table 1.1: Methods for adding comments in scripts


Method Marker Can use to Note
Double slash // Designate all text on Cannot extend to
the line to the right multiple lines
of the marker as a
comment
Slash and asterisk /*...*/ Designate the text • Can extend
between the markers over multiple
as a comment lines (multiline
comments do
Nest comments
not require a
continuation
character)

• Can be nested

Adding comment markers


In Script views and the Function painter, you can use the Comment Selection button
(or select Edit>Comment Selection from the menu bar) to comment out the line
containing the cursor or a selected group of lines.

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.

// The following statement was commented out so that it


// would not execute.
// SetNull(amt)

Slash-and-asterisk method
/* This is a single-line comment. */

/* This comment starts here,


continues to this line,
and finally ends here. */
A = B + C /* This comment starts here.
/* This is the start of a nested comment.
The nested comment ends here. */
The first comment ends here. */ + D + E + F

1.1.2 Identifier names


Description
You use identifiers to name variables, labels, functions, windows, controls, menus, and
anything else you refer to in scripts.
Syntax
Rules for identifiers:

• Must start with a letter or an _ (underscore)

• Cannot be reserved words (see Reserved words)

• Can have up to 40 characters but no spaces

• 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 ...

At the start of the line before the statement

Page 35
PowerScript Topics

FindCity: IF city=cityname[1] THEN ...

1.1.4 Special ASCII characters


Description
You can include special ASCII characters in strings. For example, you might want to include
a tab in a string to ensure proper spacing or a bullet to indicate a list item. The tilde character
(~) introduces special characters. The tab is one of the common ASCII characters that can be
entered by typing a tilde followed by a single keystroke. The bullet must be entered by typing
a tilde followed by the decimal, hexadecimal, or octal ASCII value that represents it.
Syntax
Follow the guidelines in the following table.

Table 1.2: Using special ASCII characters in strings


In this category To specify this Enter this More information
Common ASCII Newline ~n
characters
Tab ~t
Vertical tab ~v
Carriage return ~r
Form feed ~f
Backspace ~b
Double quote ~"
Single quote ~'
Tilde ~~
Any ASCII character Decimal ~### ### = a 3-digit
number from 000 to
255
Hexadecimal ~h## ## = a 2-digit
hexadecimal number
from 01 to FF
Octal ~o### ### = a 3-digit octal
number from 000 to
377

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

Using decimal, hexadecimal, and octal values


Here is how to indicate a bullet (*) in a string by using the decimal, hexadecimal, and octal
ASCII values:

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

1.1.5 NULL values


Description
Null means undefined or unknown. It is not the same as an empty string or zero or a date of
0000-00-00. For example, null is neither 0 nor not 0.
Typically, you work with null values only with respect to database values.
Usage
Initial values for variables
Although PowerBuilder supports null values for all variable datatypes, it does not initialize
variables to null. Instead, when a variable is not set to a specific value when it is declared,
PowerBuilder sets it to the default initial value for the datatype -- for example, zero for a
numeric value, false for boolean, and the empty string ("") for a string.
Null variables
A variable can become null if one of the following occurs:

• A null value is read into it from the database. If your database supports null, and a SQL
INSERT or UPDATE statement sends a null to the database, it is written to the database as
null and can be read into a variable by a SELECT or FETCH statement.

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

SetNull(city) // city is set to NULL.

Nulls in functions and expressions


Most functions that have a null value for any argument return null. Any expression that has a
variable with a null value results in null.
A boolean expression that is null is considered undefined and therefore false.
Testing for null
To test whether a variable or expression is null, use the IsNull function. You cannot use an
equal sign (=) to test for null.
Valid
This statement shows the correct way to test for null:
IF IsNull(a) THEN ...

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

1.1.6 Reserved words


The words PowerBuilder uses internally are called reserved words and cannot be used as
identifiers. If you use a reserved word as an identifier, you get a compiler warning. Reserved
words that are marked with an asterisk (*) can be used as function names.

Table 1.5: PowerScript reserved words


alias execute not step
and exit of subroutine
autoinstantiate external on super
call false open* system
case fetch or systemread
catch finally parent systemwrite
choose first post* then
close* for prepare this
commit forward prior throw
connect from private throws
constant function privateread to
continue global privatewrite trigger
create* goto procedure true
cursor halt protected try
declare if protectedread type
delete immediate protectedwrite until
describe* indirect prototypes update*
descriptor insert public updateblob
destroy into readonly using
disconnect intrinsic ref variables
do is return while
dynamic last rollback with
else library rpcfunc within
elseif loop select xor
end namespace selectblob _debug
enumerated native shared
event next static

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:

• Cause an event in an object or control

• Manipulate or change an object or control

• Obtain or change the setting of a property

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.

1.1.7.1 Parent pronoun


Description

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

• Custom user objects

• Menus

Where you use Parent determines what it references:


Window controls
When you use Parent in a script for a control (such as a CommandButton), Parent refers to
the window that contains the control.
User object controls
When you use Parent in a script for a control in a custom user object, Parent refers to the user
object.
Menus
When you use Parent in a menu script, Parent refers to the menu item on the level above the
menu the script is for.
Examples
Window controls
If you include this statement in the script for the Clicked event in a CommandButton within a
window, clicking the button closes the window containing the button:
Close(Parent)

If you include this statement in the script for the CommandButton, clicking the button
displays a horizontal scroll bar within the window (sets the HScrollBar property of the
window to true):
Parent.HScrollBar = TRUE

User object controls


If you include this statement in a script for the Clicked event for a CheckBox in a user object,
clicking the check box hides the user object:
Parent.Hide( )

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

1.1.7.2 This pronoun


Description
The pronoun This in a PowerBuilder script refers to the window, user object, menu,
application object, or control that owns the current script.
Usage
Why include This
Using This allows you to make ownership explicit. The following statement refers to the
current object's X property:
This.X = This.X + 50

When optional but helpful


In the script for an object or control, you can refer to the properties of the object or control
without qualification, but it is good programming practice to include This to make the script
clear and easy to read.
When required
There are some circumstances when you must use This. When a global or local variable has
the same name as an instance variable, PowerBuilder finds the global or local variable first.
Qualifying the variable with This allows you to refer to the instance variable instead of the
global variable.
Examples
Example 1
This statement in a script for a menu places a check mark next to the menu selection:
This.Check( )

Example 2
In this function call, This passes a reference to the object containing the script:
ReCalc(This)

Example 3
If you omit This, "x" in the following statement refers to a local variable x if there is one
defined (the script adds 50 to the variable x, not to the X property of the control). 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

1.1.7.3 Super pronoun


Description
When you write a PowerBuilder script for a descendant object or control, you can call scripts
written for any ancestor. You can directly name the ancestor in the call, or you can use the
reserved word Super to refer to the immediate ancestor.
Usage
Whether to use Super
If you are calling an ancestor function, you only need to use Super if the descendant has a
function with the same name and the same arguments as the ancestor function. Otherwise,
you would simply call the function with no qualifiers.
Restrictions for Super
You cannot use Super to call scripts associated with controls in the ancestor window. You
can only use Super in an event or function associated with a direct descendant of the ancestor
whose function is being called. Otherwise, the compiler returns a syntax error.
To call scripts associated with controls, use the CALL statement.
See the discussion of CALL.
Examples
Example 1
This example calls the ancestor function wf_myfunc (presumably the descendant also has a
function called wf_myfunc):
Super::wf_myfunc(myarg1, myarg2)

This example 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()

1.1.8 Statement continuation


Description
Although you typically put one statement on each line, you occasionally need to continue
a statement to more than one line. The statement continuation character is the ampersand
(&). (For the use of the ampersand character in accelerator keys, see the PowerBuilder Users
Guide.)

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.

• Continuing SQL statements


You do not need a continuation character to continue a SQL statement. In PowerBuilder,
SQL statements always end with a semicolon (;), and the compiler considers everything
from the start of a SQL statement to a semicolon to be part of the SQL statement. A
continuation character in a SQL statement is considered part of the statement and usually
causes an error.

Examples
Continuing a quoted string
One way
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)

1.1.9 Statement separation


Description
Although you typically put one statement on each line, you occasionally want to combine
multiple statements on a single line. The statement separation character is the semicolon (;).
Syntax
Statement1; statement2

Examples
The following line contains three short statements:
A = B + C; D = E + F; Count = Count + 1

1.1.10 White space


Description
Blanks, tabs, form feeds, and comments are forms of white space. The compiler treats white
space as a delimiter and does not consider the number of white space characters.
Usage
White space in string literals
The number of white space characters is preserved when they are part of a string literal
(enclosed in single or double quotation marks).
Dashes in identifiers
Unless you have prohibited the use of dashes in identifiers (see Identifier names), you must
surround a dash used as a minus sign with spaces. Otherwise, PowerBuilder considers the
dash as part of a variable name:
Order - Balance // Subtracts Balance from Order
Order-Balance // A variable named Order-Balance

Examples
Example 1
Here the spaces and the comment are white space, so the compiler ignores them:
A + B /*Adjustment factor */+C

Example 2
Here the spaces are within a string literal, so the compiler does not ignore them:

Page 45
PowerScript Topics

"The value of A + B is:"

1.1.11 Conditional compilation


Description
The use of conditional compilation directives causes the PowerBuilder preprocessor to parse
blocks of code before they are passed to the compiler.
Syntax
#IF { NOT } DEFINED predefined_symbols THEN
action1
{ #ELSEIF DEFINED predefined_symbols THEN
action2 }
{ #ELSE
action3 }
#END IF

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.

Table 1.8: Predefined symbols for conditional compilation


Predefined Target type Code in this processing block
symbols
PBNATIVE Standard PowerBuilder Fully parsed for the standard application and
client-server or distributed converted to blank lines for .NET targets.
applications
PBWEBSERVICE
.NET Web Service Fully parsed for .NET Web Service targets and
component targets converted to blank lines for all other targets.
DEBUG All PowerBuilder standard When a project's Enable DEBUG Symbol
and .NET targets check box is selected, code is fully parsed by
the compiler and included in the deployed

Page 46
PowerScript Topics

Predefined Target type Code in this processing block


symbols
application. The code is converted to blank
lines when the check box is cleared. The
DEBUG symbol is always defined in the
development environment.

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.

Table 1.9: Types of error messages returned by the preprocessor


Error message Description
Invalid if statement #if statement without a defined symbol, with an incorrectly defined
symbol, or without a then clause
#end if directive #if statement without an #end if statement
expected
Unexpected Caused by an #else, #elseif, or #end if statement when not preceded
preprocessor by an #if statement
directive
Preprocessor syntax Caused by including text after an #else or #end if statement when the
error text is not preceded by comment characters (//)

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.

1.2.1 Standard datatypes


The datatypes
The standard datatypes in PowerBuilder are the familiar datatypes that are used in many
programming languages, including char, integer, decimal, long, and string. In PowerScript,
you use these datatypes to declare variables or arrays.
These are the standard PowerScript datatypes, followed by a description of each:

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 Date(datetime) function to convert a DateTime value to a PowerBuilder date value


after reading from a database

• The Time(datetime) function to convert a DateTime value to a PowerBuilder time value


after reading from a database

• 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 ~~~" ~" "

The first pass results in:


He said "she said ~"Hi ~" "

The second pass results in:


she said "Hi"

The third pass results in:


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)'

Finally, PowerBuilder evaluates the property's expression, converting tilde-quote to quote,


and sets the bitmap's colors accordingly.
Example 3
There are many ways to specify quotation marks for a particular set of nested strings. The
following expressions for the Modify function all have the same end result:
"emp.Color = ~"0~tIf(stat=~~~"a~~~",255,16711680)~""
"emp.Color = ~"0~tIf(stat=~~'a~~',255,16711680)~""
"emp.Color = '0~tIf(stat=~~'a~~',255,16711680)'"
"emp.Color = ~"0~tIf(stat='a',255,16711680)~""

Rules for quotation marks and tildes


When nesting quoted strings, the following rules of thumb might help:

• 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

UnsignedInteger, UnsignedInt, or UInt


16-bit unsigned integers, from 0 to 65535.
UnsignedLong or ULong

Page 52
PowerScript Topics

32-bit unsigned integers, from 0 to 4294967295.

1.2.2 The Any datatype


General information
PowerBuilder also supports the Any datatype, which can hold any kind of value, including
standard datatypes, objects, structures, and arrays. A variable whose type is Any is a
chameleon datatype -- it takes the datatype of the value assigned to it.
Declarations and assignments
You declare Any variables just as you do any other variable. You can also declare an array of
Any variables, where each element of the array can have a different datatype.
You assign data to Any variables with standard assignment statements. You can assign an
array to a simple Any variable.
After you assign a value to an Any variable, you can test the variable with the ClassName
function and find out the actual datatype:
any la_spreadsheetdata
la_spreadsheetdata = ole_1.Object.cells(1,1).value
CHOOSE CASE ClassName(la_spreadsheetdata)
CASE "integer"
...
CASE "string"
...
END CHOOSE

These rules apply to Any assignments:

• You can assign anything into an Any variable.

• You must know the content of an Any variable to make assignments from the Any variable
to a compatible 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

la_3 = ia_1 - ia_2

If ia_1 and ia_2 contain strings, you can use the concatenation operator:
any la_3
la_3 = ia_1 + ia_2

However, if ia_1 contained a number and ia_2 contained a string, you would get an execution
error.
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

Expressions whose datatype is Any


Expressions that access data whose type is unknown when the script is compiled have a
datatype of Any. These expressions include expressions or functions that access data in an
OLE object or a DataWindow object:
myoleobject.application.cells(1,1).value
dw_1.Object.Data[1,1]
dw_1.Object.Data.empid[99]

The objects these expressions point to can change so that the type of data being accessed 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 execution time, using Any variables is slow


PowerBuilder must do much more processing to determine datatypes before it can make
an assignment or perform an operation involving Any variables. In particular, an operation
performed many times in a loop will suffer greatly if you use Any variables instead of
variables of the appropriate type.

• At compile time, using Any variables removes a layer of error checking from your
programming
The PowerBuilder compiler makes sure 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.

1.2.3 System object datatypes


Objects as datatypes
System object datatypes are specific to PowerScript. You view a list of all the system objects
by selecting the System tab in the Browser.
In building PowerBuilder applications, you manipulate objects such as windows, menus,
CommandButtons, ListBoxes, and graphs. Internally, PowerBuilder defines each of these
kinds of objects as a datatype. Usually you do not need to concern yourself with these objects
as datatypes -- you simply define the objects in a PowerBuilder painter and use them.
However, sometimes you need to understand how PowerBuilder maintains its system objects
in a hierarchy of datatypes. For example, when you need to define instances of a window,
you define variables whose datatype is window. When you need to create an instance of a
menu to pop up in a window, you define a variable whose datatype is menu.
PowerBuilder maintains its system objects in a class hierarchy. Each type of object is a class.
The classes form an inheritance hierarchy of ancestors and descendants.
Examples
All the classes shown in the Browser are actually datatypes that you can use in your
applications. You can define variables whose type is any class.
For example, the following code defines window and menu variables:
window mywin
menu mymenu

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

Because it is a CommandButton, the LastClicked variable has all the properties of a


CommandButton. After the last assignment above, LastClicked's properties have the same
values as the most recently clicked button in the window.

Page 55
PowerScript Topics

To learn more about working with instances of objects through datatypes, see About objects.

1.2.4 Enumerated datatypes


About enumerated datatypes
Like the system object datatypes, enumerated datatypes are specific to PowerScript.
Enumerated datatypes are used in two ways:

• As arguments in functions

• To specify the properties of an object or control

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.

Advantages of enumerated types


Enumerated datatypes have an advantage over standard datatypes. When an enumerated
datatype is required, the compiler checks the data and makes sure it is the correct type. For
example, if you set an enumerated datatype variable to any other datatype or to an incorrect
value, the compiler does not allow it.

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).

1.3.1 Declaring variables


General information
Before you use a variable in a PowerBuilder script, you must declare it (give it a datatype and
a name).
A variable can be a standard datatype, a structure, or an object. Object datatypes can be
system objects as displayed in the Browser or they can be objects you have defined by

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.3.1.1 Where to declare variables


Scope
You determine the scope of a PowerScript variable by selecting where you declare it.
Instance variables have additional access keywords that restrict specific scripts from
accessing the variable.
The following table shows the four scopes of variables.

Table 1.11: PowerScript variable scopes


Scope Description
Global Accessible anywhere in the application. It is independent of any object
definition.
Instance Belongs to an object and is associated with an instance of that object (you
can think of it as a property of the object). Instance variables have access
keywords that determine whether scripts of other objects can access them.
They can belong to the application object, a window, a user object, or a menu.
Shared Belongs to an object definition and exists across all instances of the object.
Shared variables retain their value when an object is closed and opened again.
Shared variables are always private. They are accessible only in scripts for
the object and for controls associated with the object. They can belong to the
application object, a window, a user object, or a menu.
Local A temporary variable that is accessible only in the script in which you define
it. When the script has finished executing, the variable constant ceases to
exist.

Global, instance, and shared declarations


Global, instance, and shared variables can be defined in the Script view of the Application,
Window, User Object, or Menu painters. Global variables can also be defined in the Function
painter:

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.

3. Type the declaration in the scripting area of the Script view.

Local declarations
You declare local variables for an object or control in the script for that object or control.
Declaring SQL 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.3.1.2 About using variables


General information
To use or set a variable's value in a PowerBuilder script, you name the variable. The variable
must be known to the compiler -- in other words, it must be in scope.
You can use a variable anywhere you need its value -- for example, as a function argument or
in an assignment statement.
How PowerBuilder looks for variables
When PowerBuilder executes a script and finds an unqualified reference to a variable, it
searches for the variable in the following order:

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 ...

Referring to instance variables


You can refer to an instance variable in a script if there is an instance of the object open in the
application. Depending on the situation, you might need to qualify the name of the instance
variable with the name of the object defining it.
Using unqualified names
You can refer to instance variables without qualifying them with the object name in the
following cases:

• For application-level variables, in scripts for the application object

• For window-level variables, in scripts for the window itself and in scripts for controls in
that window

• For user-object-level variables, in scripts for the user object itself and in scripts for controls
in that user object

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

Using qualified names


In all other cases, you need to qualify the name of the instance variable with the name of the
object using dot notation:
object.instancevariable

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

Using pronouns as name qualifiers


To avoid ambiguity when referring to variables, you might decide to always use qualified
names for object variables. Qualified names leave no doubt about whether a variable is local,
instance, or shared.
To write generic code but still use qualified names, you can use the pronouns This and Parent
to refer to objects. Pronouns keep a script general by allowing you to refer to the object
without naming it specifically.
Window variables in window scripts
In a window script, use the pronoun This to qualify the name of a window instance variable.
For example, if a window has an instance variable called index, then the following statements
are equivalent in a script for that window, as long as there is no local or global variable
named index:
index = 5
This.index = 5

Window variables in control scripts


In a script for a control in a window, use the pronoun Parent to qualify the name of a
window instance variable -- the window is the parent of the control. In this example, the two
statements are equivalent in a script for a control in that window, as long as there is no local
or global variable named "index":
index = 5
Parent.index = 5

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.

1.3.1.3 Syntax of a variable declaration


Simple syntax
In its simplest form, a PowerScript variable declaration requires only two parts: the datatype
and the variable name. For example:
datatype variablename

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 } }

Table 1.12: Variable declaration parameters


Parameter Description
access (For instance variables only) Keywords specifying the access for the variable.
(optional) For information, see Access for instance variables.
datatype The datatype of the variable. You can specify a standard datatype, a system
object, or a previously defined structure.
For blobs and decimals, you can specify the size or precision of the data by
including an optional value in brackets.
{ size } (For blobs only) A number, enclosed in braces, specifying the size in bytes
(optional) of the blob. If { size } is omitted, the blob has an initial size of zero and
PowerBuilder adjusts its size each time it is used at runtime.
If you enter a size that exceeds the declared length in a script, PowerBuilder
truncates the blob data.
{ precision } (For decimals only) A number, enclosed in braces, specifying the number of
(optional) digits after the decimal point. If you do not specify a precision, the variable
takes the precision assigned to it in the script.
variablename The name of the variable (must be a valid PowerScript identifier, as described
in Identifier names).
You can define additional variables with the same datatype by naming
additional variable names, separated by commas; each variable can have a
value.
value A literal or expression of the appropriate datatype that will be the initial value
(optional) of the variable.
Blobs cannot be initialized with a value.
For information, see Initial values for variables.

Page 60
PowerScript Topics

Examples
Declaring instance variables
integer ii_total = 100 // Total shares
date id_date // Date shares were bought

Declaring a global variable


string gs_name

Declaring shared variables


time st_process_start
string ss_process_name

Declaring local variables


string ls_city = "Boston"
integer li_count

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

1.3.1.3.1 Datatype of a variable


A PowerScript variable can be declared as one of the following datatypes:

• A standard datatype (such as an integer or string).

• An object or control (such as a window or CommandButton).

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.

1.3.1.3.2 Variable names


In a well-planned application, standards determine how you name your PowerScript
variables. Naming conventions make scripts easy to understand and help you avoid name
conflicts. A typical approach is to include a prefix that identifies the scope and the datatype
of the variable. For example, a prefix for an instance variable's name typically begins with
i (such as ii_count or is_empname), a local integer variable's name would be li_total and a
global integer variable's name would be gi_total. For information about naming conventions,
see the Section 2.1.8.3, “Naming conventions” in Users Guide.
X and Y as variable names
Although you might think of x and y as typical variable names, in PowerBuilder they are
also properties that specify an object's onscreen coordinates. If you use them as variables and
forget to declare them, you do not get a compiler error. Instead, PowerBuilder assumes you
want to move the object, which might lead to unexpected results in your application.

1.3.1.3.3 Initial values for variables


When you declare a PowerScript variable, you can accept the default initial value or specify
an initial value in the declaration.
Default values for variables
If you do not initialize a variable when you declare it, PowerBuilder sets the variable to the
default value for its datatype as shown in the following table.

Table 1.13: Default initial values for variables


For this variable datatype PowerBuilder sets this default value
Blob A blob of 0 length; an empty blob
Char (or character) ASCII value 0
Boolean false
Date 1900-01-01 (January 1, 1900)
DateTime 1900-01-01 00:00:00
Numeric (byte, integer, long, longlong, 0
decimal, real, double, UnsignedInteger, and
UnsignedLong)
String Empty string ("")
Time 00:00:00 (midnight)

Specifying a literal as a initial value


To initialize a variable when you declare it, place an equal sign (=) and a literal appropriate
for that variable datatype after the variable. For information about literals for specific
datatypes, see Standard datatypes.

Page 62
PowerScript Topics

Do not use a function's return value


You should not initialize a variable by assigning it the return value of a global user
defined function, because it might not compile correctly, or because it could lead to
confusion about the value assigned. For example, do not use:
integer i = f_return_one()

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 ls_method with the string "UPS":


string ls_method="UPS"

This example initializes ls_headers to three words separated by tabs:


string ls_headers = "Name~tAddress~tCity"

This example initializes li_a to 1 and li_c to 100, leaving li_b set to its default value of zero:
integer li_a=1, li_b, li_c=100

This example declares ld_StartDate as a date and initializes it with the date February 1, 2004:
date ld_StartDate = 2004-02-01

Specifying an expression as an initial value


You can initialize a variable with the value of an existing variable or expression, such as:
integer i = 100
integer j = i

When you do this, the second variable is initialized with the value of the expression when the
script is compiled. The initialization is not reevaluated 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( )

How shared variables are initialized


When you use a shared variable in a script, the variable is initialized when the first instance
of the object is opened. When the object is closed, the shared variable continues to exist until
you exit the application. If you open the object again without exiting the application, the
shared variable will have the value it had when you closed the object.
For example, if you set the shared variable Count to 20 in the script for a window, then close
the window, and then reopen the window without exiting the application, Count will be equal
to 20.

When using multiple instances of windows


If you have multiple instances of the window in the example above, Count will be
equal to 20 in each instance. Since shared variables are shared among all instances
of the window, changing Count in any instance of the window changes it for all
instances.

How instance variables are initialized


When you define an instance variable for a window, menu, or application object, the instance
variable is initialized when the object is opened. Its initial value is the default value for its
datatype or the value specified in the variable declarations.
When you close the object, the instance variable ceases to exist. If you open the object again,
the instance variable is initialized again.
When to use multiple instances of windows
When you build a script for one of multiple instances of a window, instance variables can
have a different value in each instance of the window. For example, to set a flag based on the
contents of the instance of a window, you would use an instance variable.
When to use shared variables instead
Use a shared variable instead of an instance variable if you need a variable that:

• Keeps the same value over multiple instances of an object

• Continues to exist after the object is closed

1.3.1.3.4 Access for instance variables


Description
The general syntax for declaring PowerScript variables (see Syntax of a variable declaration)
showed that you can specify access keywords in a declaration for an instance variable. This
section describes those keywords.
When you specify an access right for a variable, you are controlling the visibility of the
variable or its visibility access. Access determines which scripts recognize the variable's
name.
For a specified access right, you can control operational access with modifier keywords. The
modifiers specify which scripts can read the variable's value and which scripts can change it.

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

Private variable not recognized outside its object


Suppose you have defined a window w_emp with a private integer variable ii_int:
private integer ii_int

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

Public variable with restricted access

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

1.3.1.3.5 Another format for access-right keywords


Description
You can also group declarations of PowerScript variables according to access by specifying
the access-right keyword as a label. It appears on its own line, followed by a colon (:).
Syntax
access-right:
{ readaccess } { writeaccess } datatype variablename
{ access-right } { readaccess } { writeaccess } datatype variablename
{ readaccess } { writeaccess } datatype variablename

Within a labeled group of declarations, you can override the access on a single line by
specifying another access-right keyword with the declaration. The labeled access takes effect
again on the following lines.
Examples
In these declarations, the instance variables have the access specified by the label that
precedes them. Another private variable is defined at the end, where private overrides the
public label:
Private:
integer ii_a=10, ii_b=24
string is_Name, is_Address1
Protected:
integer ii_Units
double idb_Results
string is_Lname
Public:
integer ii_Weight
string is_Location="Home"
private integer ii_test

Some of these protected declarations have restricted write access:


Protected:
integer ii_Units
privatewrite double idb_Results
privatewrite string is_Lname

1.3.2 Declaring constants


Description
Any PowerScript variable declaration of a standard datatype that can be assigned an initial
value can be a constant instead of a variable. To make it a constant, include the keyword
CONSTANT in the declaration and assign it an initial value.

Page 67
PowerScript Topics

Syntax
CONSTANT { access } datatype constname = value

The following table shows the parameters used to declare constants.

Table 1.15: Constant variable declaration parameters


Parameter Description
CONSTANTDeclares a constant instead of a variable. The CONSTANT keyword can be
before or after the access keywords.
access (For instance variables only) Keywords specifying the access for the constant.
(optional) For information, see Access for instance variables.
datatype A standard datatype for the constant. For decimals, you can include an
optional value in brackets to specify the precision of the data. Blobs cannot be
constants.
For information about PowerBuilder datatypes, see Standard datatypes.
constname The name of the constant (must be a valid PowerScript identifier, as described
in Identifier names).
value A literal or expression of the appropriate datatype that will be the value of
the constant. The value is required. For information, see Initial values for
variables.

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

1.3.3 Declaring arrays


Description
An array is an indexed collection of elements of a single datatype. In PowerBuilder, an array
can have one or more dimensions. One-dimensional arrays can have a fixed or variable size;
multidimensional arrays always have a fixed size. Each dimension of an array can have
2,147,483,647 bytes of elements.
Any simple variable declaration becomes an array when you specify brackets after the
variable name. For fixed-size arrays, you specify the sizes of the dimensions inside those
brackets.
Syntax
{ access } datatype variablename { d1, ..., dn } { = { valuelist } }

Page 68
PowerScript Topics

The following table describes the parameters used to declare array variables.

Table 1.16: Array variable declaration parameters


ParameterDescription
access (For instance variables only) Keywords specifying the access for the variable.
(optional) For information, see Access for instance variables.
datatype The datatype of the variable. You can specify a standard datatype, a system
object, or a previously defined structure.
For decimals, you can specify the precision of the data by including an optional
value in brackets after datatype (see Syntax of a variable declaration):
decimal {2} variablename [ ]

For blobs, fixed-length blobs within an array are not supported. If you specify a
size after datatype, it is ignored.
variablename
The name of the variable (name must be a valid PowerScript identifier, as
described in Identifier names).
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.

Using TO to change array index values


These fixed-size arrays use TO to change the range of index values for the array:
real lr_Rate[2 to 5] // Array of 4 real numbers:
// Rate[2] through Rate[5]
integer li_Qty[0 to 2] // Array of 3 integers
string ls_Test[-2 to 2] // Array of 5 strings
integer li_year[76 to 96] // Array of 21 integers
string ls_name[-10 to 15] // Array of 26 strings

Incorrect declarations using TO


In an array dimension, the second number must be greater than the first. These declarations
are invalid:
integer li_count[10 to 5] // INVALID: 10 is
// greater than 5
integer li_price[-10 to -20] // INVALID: -10
// is greater than -20

Arrays with two or more dimensions


This declaration creates a six-element, two-dimensional integer array. The individual
elements are li_score[1,1], li_score[1,2], li_score[1,3], li_score[2,1], li_score[2,2], and
li_score[2,3]:
integer li_score[2,3]

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]

This declaration creates a 3-dimensional 45,000-element array:

Page 70
PowerScript Topics

long ll_days[3, 300, 50]

This declaration changes the subscript range for the second and third dimension:
integer li_staff[100, 0 to 20, -5 to 5]

More declarations of multidimensional arrays:


string ls_plant[3,10] // two-dimensional array
// of 30 strings
dec{2} lc_rate[3,4] // two-dimensional array of 12
// decimals with 2 digits
// after the decimal point

This declaration creates three decimal arrays:


decimal{3} lc_first[10],lc_second[15,5],lc_third[ ]

1.3.3.1 Values for array elements


General information
PowerBuilder initializes each element of an array to the same default value as its underlying
datatype. For example, in a newly declared integer array:
integer li_TaxCode[3]

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

real lr_Rate[3]={1.20, 2.40, 4.80}

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

1.3.3.2 Size of variable-size arrays


General information
A variable-size array consists of a variable name followed by square brackets but no number.
PowerBuilder defines the array elements by use at execution time (subject only to memory
constraints). Only one-dimensional arrays can be variable-size arrays.
Because you do not declare the size, you cannot use the TO notation to change the lower
bound of the array, so the lower bound of a variable-size array is always 1.
How memory is allocated
Initializing elements of a variable-size array allocates memory for those elements. You
specify initial values just as you do for fixed-size arrays, by listing the values in braces. The
following statement sets code[1] equal to 11, code[2] equal to 242, and code[3] equal to
27. The array has a size of 3 initially, but the size will change if you assign values to higher
positions:
integer li_code[ ]={11,242,27}

For example, these statements declare a variable-size array and assigns values to three array
elements:
long ll_price[ ]
ll_price[100] = 2000

Page 72
PowerScript Topics

ll_price[50] = 3000
ll_price[110] = 5000

When these statements first execute, they allocate memory as follows:

• The statement ll_price[100]=2000 will allocate memory for 100 long numbers ll_price[1]
to ll_price[100], then assign 0 (the default for numbers) to ll_price[1] through ll_price[99]
and assign 2000 to ll_price[100].

• The statement ll_price[50]=3000 will not allocate more memory but will assign the value
3000 to the 50th element of the ll_price array.

• The statement ll_price[110]=5000 will allocate memory for 10 more long numbers named
ll_price[101] to ll_price[110] and then assign 0 (the default for numbers) to ll_price[101]
through ll_price[109] and assign 5000 to ll_price[110].

1.3.3.3 More about arrays


This section provides technical details about:

• Assigning one array to another

• Using arraylists to assign values to an array

• Errors that occur when addressing arrays

1.3.3.3.1 Assigning one array to another


General information
When you assign one array to another, PowerBuilder uses the following rules to map the
values of one onto the other.
One-dimensional arrays
To an unbounded array
The target array is the same as the source:
integer a[ ], b[ ]
a = {1,2,3,4}
b = a

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

One-dimensional array to a multidimensional array


A one-dimensional array can be assigned to a multidimensional array. The values are mapped
onto the multidimensional array in column major order:
integer a[ ], b[2,2]
b = a

Multidimensional array to a one-dimensional array


A multidimensional array can also be assigned to a one-dimensional array. The source is
linearized in column major order and assigned to the target:
integer a[ ], b[2,2]
a = b

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}

Array b is laid out like this:

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

This statement explicitly linearizes b into c:

Page 74
PowerScript Topics

c = b

You can then assign the linearized version of the array to a:


a = c

The values in array a are laid out like this:

Table 1.18:
1 for a[1,1] 3 for a[1,2]
2 for a[2,1] 4 for a[2,2]

Initializing a with an arraylist produces the same result:


integer a[2,2] = {1,2,3,4}

The following section describes arraylists.

1.3.3.3.2 Using arraylists to assign values to an array


General information
In PowerBuilder, an arraylist is a list of values enclosed in braces used to initialize arrays.
An arraylist represents a one-dimensional array, and its values are assigned to the target array
using the rules for assigning arrays described in Assigning one array to another.
Examples
In this declaration, a variable-size array is initialized with four values:
integer a[ ] = {1,2,3,4}

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

1.3.3.3.3 Errors that occur when addressing arrays


Fixed-size arrays
In PowerBuilder, referring to array elements outside the declared size causes an error at
runtime; for example:
int test[10]
test[11]=50 // This causes an execution error.
test[0]=50 // This causes an execution error.
int trial[5,10]
trial [6,2]=75 // This causes an execution error.
trial [4,11]=75 // This causes an execution error.

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.

1.3.4 Declaring external functions


Description
External functions are functions written in languages other than PowerScript and stored
in dynamic link libraries. On Windows, dynamic libraries have the extension DLL. If you
deploy a component written in PowerBuilder to a UNIX server, the dynamic libraries it calls
have the extension .so, .sl, or .a, depending on the UNIX operating system. You can use
external functions that are written in any language that supports dynamic libraries.
Before you can use an external function in a script, you must declare it as one of two types:

• Global external functions


These are available anywhere in the application.

• Local external functions


These are defined for a particular type of window, menu, user object, or user-defined
function. These functions are part of the object's definition and can always be used in
scripts for the object itself. You can also choose to make these functions accessible to other
scripts.

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}"

External subroutine syntax


To declare external subroutines (which are the same as external functions except that they do
not return a value), use this syntax:
{ access } SUBROUTINE 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:

Table 1.21: External function or subroutine declaration parameters


Parameter Description
access (Local external functions only) Public, Protected, or Private specifies the
(optional) access level of a local external function. The default is Public.
For more information, see the section about specifying access of local
functions in Usage.
FUNCTION or A keyword specifying the type of call, which determines the way return
SUBROUTINE values are handled. If there is a return value, declare it as a FUNCTION; if
it returns nothing or returns VOID, specify SUBROUTINE.
returndatatype The datatype of the value returned by the function.
name The name of a function or subroutine that resides in a DLL. Function
names cannot contain special characters, such as the @ character, because
they cause a compiler error. Use the ALIAS FOR clause described later in
this table if the function name in the DLL contains special characters.
REF A keyword that specifies that you are passing by reference the argument
that follows REF. The function can store a value in arg that will be
accessible to the rest of the PowerBuilder script.
datatype arg The datatype and name of the arguments for the function or subroutine.
The list must match the definition of the function in the DLL. Each
datatype arg pair can be preceded by REF.
For more information on passing arguments, see Section 5.5.1.3, “Passing
arguments” in Application Techniques.
LIBRARY A keyword followed by a string containing the name of the dynamic
"libname" library in which the function or subroutine is stored. libname is a dynamic
link library, which is a file that usually has the extension DLL on
Windows.
ALIAS FOR Keywords followed by a string giving the name of the function as defined
"extname" (optional)
in the dynamic library. If the name in the dynamic library is not the name

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:

Table 1.22: Access levels for local external functions


Access level Where you can use the local external function
Public Any script in the application.
Private Scripts for events in the object for which the function is declared. You
cannot use the function in descendants of the object.
Protected Scripts for the object for which the function is declared and its descendants.

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:

• The current directory

• The Windows directory

• The Windows System subdirectory

• Directories on the DOS path

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"

A function called uf_playsound in the examples application provided with PowerBuilder


calls the external functions. Uf_playsound is called with two arguments (as_filename and
ai_option) that are passed through to sndPlaySoundA.
Values for ai_option are as defined in the Windows documentation, as commented here:
//Options as defined in mmystem.h.
//These may be or'd together.
//#define SND_SYNC 0x0000
//play synchronously (default)
//#define SND_ASYNC 0x0001
//play asynchronously
//#define SND_NODEFAULT 0x0002
//do not use default sound
//#define SND_MEMORY 0x0004
//lpszSoundName points to a memory file
//#define SND_LOOP 0x0008
//loop the sound until next sndPlaySound
//#define SND_NOSTOP 0x0010
//do not stop any currently playing sound

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 declaration uses longptr instead of ulong:


FUNCTION longptr FindWindowW (ulong classname, string windowname) 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

1.3.4.1 Datatypes for external function arguments


When you declare an external function in PowerBuilder, the datatypes of the arguments must
correspond with the datatypes as declared in the function's source definition. This section
documents the correspondence between datatypes in external functions and datatypes in
PowerBuilder. It also includes information on byte alignment when passing structures by
value.
Use the tables to find out what PowerBuilder datatype to use in an external function
declaration. The PowerBuilder datatype you select depends on the datatype in the source code
for the function. The first column lists datatypes in source code. The second column describes
the datatype so you know exactly what it is. The third column lists the PowerBuilder datatype
you should use in the external function declaration.
Boolean
BOOL and Boolean on Windows are 16-bit, signed. Both are declared in PowerBuilder as
boolean.
Pointers
Table 1.23: PowerBuilder datatypes for pointers
Datatype in source code Size, sign, precision PowerBuilder datatype
* (any pointer) 32-bit pointer Long
char * Array of bytes of variable Blob
length

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

The Windows 32-bit FAR pointer LPSTR is declared in PowerBuilder as string.

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

Table 1.25: PowerBuilder datatypes for fixed-point values


Datatype in source code Size, sign, precision PowerBuilder datatype
byte 8 bits, unsigned Byte
short 16 bits, signed Integer
unsigned short 16 bits, unsigned UnsignedInteger
int 32 bits, signed Long
unsigned int 32 bits, unsigned UnsignedLong
long 32 bits, signed Long
unsigned long 32 bits, unsigned UnsignedLong
longlong 64 bits, signed LongLong

The Windows definition WORD is declared in PowerBuilder as UnsignedInteger and the


Windows definition DWORD is declared as an UnsignedLong. You cannot call external
functions with return values or arguments of type short.
Floating-point values
Table 1.26: PowerBuilder datatypes for floating-point values
Datatype in source code Size, sign, precision PowerBuilder datatype
float 32 bits, single precision Real
double 64 bits, double precision Double

PowerBuilder does not support 80-bit doubles on Windows.


Date and time
The PowerBuilder datatypes Date, DateTime, and Time are structures and have no direct
equivalent for external functions in C.
Passing structures by value
You can pass PowerBuilder structures to external C functions if they have the same
definitions and alignment as the structure's components. The DLL or shared library must be
compiled using byte alignment; no padding is added to align fields within the structure.
Using 1-byte structure member alignment in external function
When you use a structure or structure array as parameters to external function in the older
versions of PowerBuilder, the structure member alignment was one byte. However, the
default alignment is 8 bytes on Windows platform, which means that most (if not all)
Windows standard APIs use this value to align arguments with structure members. This
will cause a mismatch between Windows APIs and PB applications in PowerBuilder 12.5
and earlier versions. A well adopted solution to this issue was to add some bytes within
PowerBuilder structures manually to fill those gaps. Such gap filling can be complex and
error-prone if involving complex nested structures. And what is worse, this solution fails
with the introduction of 64-bit application development in PowerBuilder 12.6 because the
number of bytes you have to fill may be different between 64-bit and 32-bit applications. This
was the major reason to make this change in PowerBuilder 12.6. With PowerBuilder 12.6 for
Windows API and Visual C++ the default structure member alignment is now 8 bytes. The
structure member alignment was changed to 8 bytes in PowerBuilder 12.6 for both 64-bit and

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.

1.3.4.2 Calling external functions


Global external functions
In PowerBuilder, you call global external functions using the same syntax as for calling user-
defined global and system functions. As with other global functions, global external functions
can be triggered or posted but not called dynamically.
Local external functions
Call local functions using the same syntax as for calling object functions. They can be
triggered or posted and called dynamically.
For information
For information, see Syntax for calling PowerBuilder functions and events.

1.3.4.3 Defining source for external functions


You can use external functions written in any language that supports the standard calling
sequence for 32-bit platforms. If you are calling functions on Windows in libraries that
you have written yourself, remember that you need to export the functions. Depending on
your compiler, you can do this in the function prototype or in a linker definition (.DEF) file.
For more information about using external functions, see Section 5.5.1, “Using external
functions” in Application Techniques.
Use _stdcall convention
C and C++ compilers typically support several calling conventions, including _cdecl (the
default calling convention for C programs), _stdcall (the standard convention for Windows
API calls), _fastcall, and thiscall. PowerBuilder, like many other Windows development
tools, requires external functions to be exported using the WINAPI (_stdcall) format.
Attempting to use a different calling convention can cause an application crash.
When you create your own C or C++ DLLs containing functions to be used in PowerBuilder,
make sure that they use the standard convention for Windows API calls.
For example, if you are using a DEF file to export function definitions, you can declare the
function like this:

Page 82
PowerScript Topics

LONG WINAPI myFunc()


{
...
};

1.3.5 Declaring DBMS stored procedures as remote procedure calls


Description
In PowerBuilder, you can use dot notation for calling non-result-set stored procedures as
remote procedure calls (RPCs):
object.function

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" }

Table 1.27: RPC declaration parameters


Argument Description
FUNCTION or A keyword specifying the type of call, which determines the way return
SUBROUTINE values are handled. If there is a return value, declare it as a FUNCTION. If
it returns nothing or returns VOID, specify SUBROUTINE.
rtndatatype In a FUNCTION declaration, the datatype of the value returned by the
function.
functionname The name of the database procedure as you will call it in PowerBuilder.
If the name in the DBMS is different, use ALIAS FOR to associate the
DBMS name with the PowerBuilder name.
REF Specifies that you are passing by reference the argument that follows REF.
The stored procedure can store a value in arg that will be accessible to the
rest of the PowerBuilder script.
When you pass a string 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.
datatype arg The datatype and name of the arguments for the stored procedure. The list
must match the definition of the stored procedure in the database. Each
datatype arg pair can be preceded by REF.

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"

This code calls the function in a script:


double val = 20000
double rv
rv = SQLCA.give_raise(val)

Example 2
This declaration for the stored procedure SPM8 does not need an ALIAS FOR phrase,
because the PowerBuilder and DBMS names are the same:
FUNCTION integer SPM8(integer value) RPCFUNC

This code calls the SPM8 stored procedure:


int myresult
myresult = SQLCA.spm8(myresult)
IF SQLCA.sqlcode <> 0 THEN
messagebox("Error", SQLCA.sqlerrtext)
END IF

1.4 Operators and Expressions


About this chapter

Page 84
PowerScript Topics

This chapter describes the operators supported in PowerScript and how to use them in
expressions.

1.4.1 Operators in PowerBuilder


General information
Operators perform arithmetic calculations; compare numbers, text, and boolean values;
execute relational operations on boolean values; and concatenate strings and blobs.
Three types
PowerScript supports three types of operators:

• Arithmetic operators for numeric datatypes

• Relational operators for all datatypes

• Concatenation operator for string datatypes

Operators used in DataWindow objects


The documentation for DataWindows describes how operators are used in
DataWindow expressions.

1.4.1.1 Arithmetic operators in PowerBuilder


Description
The following table lists the arithmetic operators used in PowerBuilder.

Table 1.28: PowerBuilder arithmetic operators


Operator Meaning Example
+ Addition Total=SubTotal+Tax
- Subtraction Price=Price-Discount
Unless you have prohibited the use of dashes in identifier
names, you must surround the minus sign with spaces.
* Multiplication Total=Quantity*Price
/ Division Factor=Discount/Price
^ Exponentiation Rank=Rating^2.5

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

For information about dashes in identifiers, see Identifier names.


Multiplication and division
Multiplication and division are carried out to full precision (16-28 digits). Decimal numbers
are rounded (not truncated) on assignment.
Calculation with NULL
When you form an arithmetic expression that contains a NULL value, the expression's value
is null. Thinking of null as undefined makes this easier to understand.
For more information about null values, see NULL values.
Errors and overflows
The following problems can occur when using arithmetic operators:

• Division by zero, exponentiation of negative values, and so on cause errors at runtime.

• Overflow of real, double, and decimal values causes errors at runtime.

• 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

Precision for division


These examples show the values that result from various operations on decimal values:
decimal {4} a,b,d,e,f
decimal {3} c
a = 20.0/3 // a contains 6.6667
b = 3 * a // b contains 20.0001
c = 3 * a // c contains 20.000
d = 3 * (20.0/3) // d contains 20.0000
e = Truncate(20.0/3, 4) // e contains 6.6666
f = Truncate(20.0/3, 5) // f contains 6.6667

Calculations with null


When the value of variable c is null, the following assignment statements all set the variable a
to null:
integer a, b=100, c

SetNULL(c)

Page 86
PowerScript Topics

a = b+c // all statements set a to NULL


a = b - c
a = b*c
a = b/c

Overflow
This example illustrates the value of the variable i after overflow occurs:
integer i
i = 32767
i = i + 1 // i is now -32768

1.4.1.2 Relational operators in PowerBuilder


Description
PowerBuilder uses relational operators in boolean expressions to evaluate two or more
operands. Logical operators can join relational expressions to form more complex boolean
expressions.
The result of evaluating a boolean expression is always true or false.
The following table lists relational and logical operators.

Table 1.29: PowerBuilder relational and logical operators


Operator Meaning Example
= Equals if Price=100 then Rate=.05
> Greater than if Price>100 then Rate=.05
< Less than if Price<100 then Rate=.05
<> Not equal if Price<>100 then Rate=.05
>= Greater than or equal if Price>=100 then Rate=.05
<= Less than or equal if Price<=100 then Rate=.05
NOT Logical negation if NOT Price=100 then
Rate=.05
AND Logical and if Tax>3 AND Ship <5 then
Rate=.05
OR Logical or if Tax>3 OR Ship<5 then
Rate=.05

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

Trailing blanks in comparisons


In this example, trailing blanks in one string cause the comparison to fail:
City1 = "Austin"
City2 = "Austin "
IF City1 = City2 ... // Returns FALSE

Logical expressions with null values


In this example, the expressions involving the variable f, which has been set to null, have null
values:
boolean d, e = TRUE, f
SetNull(f)
d = e and f // d is NULL
d = e or f // d is TRUE

1.4.1.3 Concatenation operator in PowerBuilder


Description
The PowerBuilder concatenation operator joins the contents of two variables of the same type
to form a longer value. You can concatenate strings and blobs.
The following table shows the concatenation operator.

Table 1.30: PowerBuilder concatenation operator


Operator Meaning Example
+ Concatenate "cat " + "dog"

Examples
Example 1

Page 88
PowerScript Topics

These examples concatenate several strings:


string Test
Test = "over" + "stock" // Test contains "overstock"
string Lname, Fname, FullName
FullName = Lname + ', ' + Fname
// FullName contains last name and first name,
// separated by a comma and space.

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

1.4.2 Operator precedence in PowerBuilder expressions


Order of precedence
To ensure predictable results, all operators in a PowerBuilder expression are evaluated in a
specific order of precedence. When the operators have the same precedence, PowerBuilder
evaluates them left to right.
These are the operators in descending order of precedence:

Table 1.31: Order of precedence of operators


Operator Purpose
() Grouping (see note below on overriding)
+, - Unary plus and unary minus (indicates
positive or negative number)
^ Exponentiation
*, / Multiplication and division
+, - Addition and subtraction; string
concatenation
=, >, <, <=, >=, <> Relational operators
NOT Negation
AND Logical and
OR Logical or

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

1.4.3 Datatype of PowerBuilder expressions


General information
The datatype of an expression is important when it is the argument for a function or event.
The expression's datatype must be compatible with the argument's definition. If a function is
overloaded, the datatype of the argument determines which version of the function to call.
There are three types: numeric, string, and char datatypes.

1.4.3.1 Numeric datatypes in PowerBuilder


General information
All numeric datatypes are compatible with each other.
What PowerBuilder does
PowerBuilder converts datatypes as needed to perform calculations and make assignments.
When PowerBuilder evaluates a numeric expression, it converts the datatypes of operands to
datatypes of higher precedence according to the operators and the datatypes of other values in
the expression.

1.4.3.1.1 Datatype promotion when evaluating numeric expressions


Order of precedence
The PowerBuilder numeric datatypes are listed here in order of highest to lowest precedence
(the order is based on the range of values for each datatype):
Double
Real
Decimal
LongLong
UnsignedLong
Long
UnsignedInteger
Integer
Byte
Rules for type promotion
Datatypes of operands
If operands in an expression have different datatypes, the value whose type has lower
precedence is converted to the datatype with higher precedence.
Unsigned versus signed
Unsigned has precedence over signed, so if one operand is signed and the other is unsigned,
both are promoted to the unsigned version of the higher type. For example, if one operator is
a long and another UnsignedInteger, both are promoted to UnsignedLong.
Operators
The effects of operators on an expression's datatype are:

• +, -, *

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.

Table 1.32: Datatypes of literal operands in an expression


Literal Datatype
Integer literals (no decimal point or Long
exponent) within the range of Long
Integer literals beyond the range of Long and UnsignedLong
within the range of UnsignedLong
Integer literals beyond the range of LongLong
UnsignedLong and within the range of
LongLong
Numeric literals with a decimal point (but no Decimal
exponent)
Numeric literals with a decimal point and Double
explicit exponent

Out of range
Integer literals beyond the range of LongLong cause compiler errors.

1.4.3.1.2 Assignment and datatypes


General information
Assignment is not part of expression evaluation. In an assignment statement, the value of an
expression is converted to the datatype of the left-hand variable. In the expression
c = a + b

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 final value of d is 33000. The calculation proceeds like this:


Convert integer a to long
Convert integer b to long
Add the longs a and b
Assign the result to the long d
Because the variable d is a long, the value 33000 does not cause overflow.
Example 2
In contrast, consider this code with an assignment to an integer variable:
integer a = 32000, b = 1000, c
long e
c = a + b
e = c

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.

1.4.3.2 String and char datatypes in PowerBuilder


General information
There is no explicit char literal type.
String literals convert to type char using the following rules:

• 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"

results in the character x being assigned to the char variable c.

• 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.

Assigning strings to char arrays


As with other datatypes, you can use arrays of chars. Assigning strings to char arrays follows
these rules:

• If the char array is unbounded (defined as a variable-size array), the contents of the string
are copied directly into the char array.

• If the char array is bounded and its length is less than or equal to the length of the string,
the string is truncated in the array.

• If the char array is bounded and its length is greater than the length of the string, the entire
string is copied into the array along with its zero terminator. Remaining characters in the
array are undetermined.

Assigning char arrays to strings


When a char array is assigned to a string variable, the contents of the array are copied into the
string up to a zero terminator, if found, in the char array.
Using both strings and chars in an expression
Expressions using both strings and char arrays promote the chars to strings before evaluation.
For example, the following promotes the contents of c to a string before comparison with the
string "x":
char c
. . .
if (c = "x") then

Using chars in PowerScript functions


All PowerScript functions that take strings also take chars and char arrays, subject to the
conversion rules described above.

1.5 Structures and Objects


About this chapter
This chapter describes basic concepts for structures and objects and how you define, declare,
and use them in PowerScript.

1.5.1 About structures


General information
A structure is a collection of one or more variables (sometimes called elements) that you
want to group together under a single name. The variables can have any datatype, including
standard and object datatypes and other structures.
Defining structures

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

Referring to structure variables


In scripts, you refer to the structure's variables using dot notation:
structurename.variable

These statements assign values to the variables in str_emp_data:


str_emp1.emp_id = 100
str_emp1.emp_lname = "Jones"
str_emp1.emp_salary = 200

str_emp2.emp_id = 101
str_emp2.emp_salary = str_emp1.salary * 1.05

Using structures as instance variables


If the structure is declared as part of an object, you can qualify the structure name using dot
notation:
objectname.structurename.variable

Suppose that this declaration is an instance variable of the window w_customer:


str_cust_data str_cust1

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

1.5.2 About objects


What an object is
In object-oriented programming, an object is a self-contained module containing state
information and associated methods. Most entities in PowerBuilder are objects: visual objects

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.

1.5.2.1 About user objects


Two types
There are two major types of user objects: visual and class.
Visual user objects
A visual user object is a reusable control or set of controls that has a certain behavior. There
are three types -- standard, custom, and external.

Table 1.33: Visual user object types


Visual user Description
objects
Standard Inherited from a specific visual control. You can set properties and write
scripts so that the control is ready for use.
It has the same events and properties as the control it is inherited from plus
any that you add.

Page 95
PowerScript Topics

Visual user Description


objects
Custom Inherited from the UserObject system class. You can include many controls
in the user object and write scripts for their events.
Each control in the user object has the same events and properties as the
controls from which they are inherited plus any that you add.
External A user object that displays a visual control defined in a DLL. The control is
not part of the PowerBuilder object hierarchy. The DLL developer provides
information for setting style bits that control its presentation.
Its events, functions, and properties are specified by the developer of the
DLL.
An external user object is not the same as an OCX, which you can put in an
OLE control.

Class user objects


Class user objects consist of properties, functions, and sometimes events. They have no
visual component. There are two types -- standard and custom.

Table 1.34: Class user object types


Class user Description
objects
Standard Inherits its definition from a nonvisual PowerBuilder object, such as the
Transaction or Error object. You can add instance variables and functions.
A few nonvisual objects have events to write scripts for these events, you
have to define a class user object.
Custom An object of your own design for which you define instance variables,
events, and functions in order to encapsulate application-specific
programming in an object.

For information on defining and using user objects, see the Section 4.7, “Working with User
Objects” in Users Guide.

1.5.2.2 Instantiating objects


Classes versus instances
Because of the way PowerBuilder object classes and instances are named, it is easy to think
they are the same thing. For example, when you define a window in the Window painter, you
are defining an object class.
One instance
When you open a window with the simplest format of the Open function, you are
instantiating an object instance. Both the class definition and the instance have the same
name. In your application, w_main is a global variable of type w_main:
Open(w_main)

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.

1.5.2.3 Using ancestors and descendants


descendant objects
In PowerBuilder, an object class can be inherited from another class. The inherited or
descendant object has all the instance variables, events, and functions of the ancestor. You
can augment the descendant by adding more variables, events, and functions. If you change
the ancestor, even after editing the descendant, the descendant incorporates the changes.
Instantiating
When you instantiate a descendant object, PowerBuilder also instantiates all its ancestor
classes. You do not have programmatic access to these ancestor instances, except in a few
limited ways, such as when you use the scope operator to access an ancestor version of a
function or event script.

1.5.2.4 Garbage collection


What garbage collection does
The PowerBuilder garbage collection mechanism checks memory automatically for
unreferenced and orphaned objects and removes any it finds, thus taking care of most
memory leaks. You can use garbage collection to destroy objects instead of explicitly
destroying them using the DESTROY statement. This lets you avoid runtime errors that
occur when you destroy an object that was being used by another process or had been passed
by reference to a posted event or function.
When garbage collection occurs

Page 97
PowerScript Topics

Garbage collection occurs:

• When a reference is removed from an object


A reference to an object is any variable whose value is the object. When the variable goes
out of scope, or when it is assigned a different value, PowerBuilder removes a reference to
the object, counts the remaining references, and destroys the object if no references remain.

• When the garbage collection interval is exceeded


When PowerBuilder completes the execution of a system-triggered event, it makes a
garbage collection pass if the set interval between garbage collection passes has been
exceeded. The default interval is 0.5 seconds. The garbage collection pass removes
any objects and classes that cannot be referenced, including those containing circular
references (otherwise unreferenced objects that reference each other).
When you post an event or function and pass an object reference, PowerBuilder adds an
internal reference to the object to prevent it from being collected between the time of the
post and the actual execution of the event or function. This reference is removed when the
event or function is executed.

Exceptions to garbage collection


There are a few objects that are prevented from being collected:

• Visual objects
Any object that is visible on your screen is not collected because when the object is created
and displayed on your screen, an internal reference is added to the object. When any visual
object is closed it is explicitly destroyed.

• Timing objects
Any Timing object that is currently running is not collected because the Start function for a
Timing object adds an internal reference. The Stop function removes the reference.

• Shared objects
Registered shared objects are not collected because the SharedObjectRegister function
adds an internal reference. SharedObjectUnregister removes the internal reference.

Controlling when garbage collection occurs


Garbage collection occurs automatically in PowerBuilder, but you can use the functions
GarbageCollect, GarbageCollectGetTimeLimit, and GarbageCollectSetTimeLimit to force
immediate garbage collection or to change the interval between reference count checks.
By setting the interval between garbage collection passes to a very large number, you can
effectively turn off garbage collection.

1.5.2.5 User objects that behave like structures


In PowerBuilder, a nonvisual user object can provide functionality similar to that of a
structure. Its instance variables form a collection similar to the variables for the structure. In
scripts, you use dot notation to refer to the user object's instance variables, just as you do for
structure variables.

Page 98
PowerScript Topics

Advantages of user objects


The user object can include functions and its own structure definitions, and it allows you to
inherit from an ancestor class. None of this is possible with a structure definition.
Memory allocation differences
Memory allocation is different for user objects and structures. An object variable is a
reference to the object. Declaring the variable does not allocate memory for the object. After
you declare it, you must instantiate it with a CREATE statement. Assignment for a user
object is also different (described in Assignment for objects and structures).
Autoinstantiated objects
If you want a user object that has methods and inheritance but want the memory allocation of
a structure, you can define an autoinstantiated object.
You do not have to create and destroy autoinstantiated objects. Like structures, they are
created when they are declared and destroyed when they go out of scope. However, because
assignment for autoinstantiated objects behaves like structures, the copies made of the object
can be a drawback.
To make a custom class user object autoinstantiated, select the Autoinstantiate check box on
the user object's property sheet.

1.5.3 Assignment for objects and structures


In PowerBuilder, assignment for objects is different from assignment for structures or
autoinstantiated objects:

• 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

1.5.3.1 Assignment for structures


Declaring a structure variable creates an instance of that structure:
str_emp_data str_emp1, str_emp2 // Two structure instances

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.

1.5.3.2 Assignment for objects


Declaring an object variable declares an object reference:
uo_emp_data uo_emp1, uo_emp2 // Two object references

Using the CREATE statement creates an instance of the object:


uo_emp1 = CREATE uo_emp_data

When you assign one object variable to another, a reference to the object instance is copied.
Only one copy of the object exists:
uo_emp2 = uo_emp1 // Both point to same object instance

Ancestor and descendant objects


Assignments between ancestor and descendant objects occur in the same way, with an object
reference being copied to the target object.
Suppose that uo_emp_data is an ancestor user object of uo_emp_active and uo_emp_inactive.
Declare variables of the ancestor type:
uo_emp_data uo_emp1, uo_emp2

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.

1.5.3.3 Assignment for autoinstantiated user objects


Declaring an autoinstantiated user object creates an instance of that object (just like a
structure). The CREATE statement is not allowed for objects with the Autoinstantiate setting.
In the following example, uo_emp_data has the Autoinstantiate setting:
uo_emp_data uo_emp1, uo_emp2 // Two object instances

When you assign an autoinstantiated object to another autoinstantiated object, the whole
object is copied to the second variable:
uo_emp1 = uo_emp2

You never have multiple references to an autoinstantiated user object.


Passing to a function

Page 100
PowerScript Topics

When you pass an autoinstantiated user object to a function, it behaves like a structure:

• Passing by value passes a copy of the object.

• 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.

Restrictions for copying


Assignments are allowed between autoinstantiated user objects only if the object types match
or if the target is a nonautoinstantiated ancestor.
Rule 1
If you assign one autoinstantiated object to another, they must be of the same type.
Rule 2
If you assign an autoinstantiated descendant object to an ancestor variable, the ancestor
cannot have the Autoinstantiate setting. The ancestor variable will contain a reference to a
copy of its descendant.
Rule 3
If you assign an ancestor object to a descendant variable, the ancestor must contain an
instance of the descendant or an execution error occurs.
Examples
To illustrate, suppose you have these declarations. Uo_emp_active and uo_emp_inactive are
autoinstantiated objects that are descendants of non-autoinstantiated uo_emp_data:
uo_emp_data uo_emp1 // Ancestor
uo_emp_active uo_empa, uo_empb // Descendants
uo_emp_inactive uo_empi // Another descendant

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.

1.6 Calling Functions and Events


About this chapter
This chapter provides background information that will help you understand the different
ways you can use functions and events. It then provides the syntax for calling functions and
events.

1.6.1 About functions and events


Importance of functions and events
Much of the power of the PowerScript language resides in the built-in PowerScript functions
that you can use in expressions and assignment statements.
Types of functions and events
PowerBuilder objects have built-in events and functions. You can enhance objects with your
own user-defined functions and events, and you can declare local external functions for an
object. The PowerScript language also has system functions that are not associated with any
object. You can define your own global functions and declare external functions and remote
procedure calls.
The following table shows the different types of functions and events.

Table 1.35: Types of functions and events


Category
Item Definition
Events Event An action in an object or control that can start the execution of a
script. A user can initiate an event by an action such as clicking an
object or entering data, or a statement in another script can initiate
the event.
User event An event you define to add functionality to an object. You specify
the arguments, return value, and whether the event is mapped to a
system message. For information about defining user events, see
Section 3.3.2, “Defining user events” in Users Guide.
System or An event that is part of an object's PowerBuilder definition. System
built-in event events are usually triggered by user actions or system messages.
PowerBuilder passes a predefined set of arguments for use in the
event's script. System events either return a long or do not have a
return value.
Functions
Function A program or routine that performs specific processing.
System A built-in PowerScript function that is not associated with an object.
function
Object A function that is part of an object's definition. PowerBuilder has
function many predefined object functions and you can define your own.

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.

Comparing functions and events


Functions and events have the following similarities:

• Both functions and events have arguments and return values.

• You can call object functions and events dynamically or statically. Global or system
functions cannot be called dynamically.

• You can post or trigger a function or event call.

Functions and events have the following differences:

• 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.

• Object-level functions can be overloaded. Events (and global functions) cannot be


overloaded.

• 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.

1.6.2 Finding and executing functions and events


PowerBuilder looks for a matching function or event based on its name and its argument
list. PowerBuilder can make a match between compatible datatypes (such as all the numeric
types). The match does not have to be exact. PowerBuilder ranks compatible datatypes to
quantify how closely one datatype matches another.
A major difference between functions and events is how PowerBuilder looks for them.

1.6.2.1 Finding functions


When calling a function, PowerBuilder searches until it finds a matching function and
executes it -- the search ends. Using functions with the same name but different arguments
is called function overloading. For more information, see Overloading, overriding, and
extending functions and events.
Unqualified function names
If you do not qualify a function name with an object, PowerBuilder searches for the function
and executes the first one it finds that matches the name and arguments. It searches for a
match in the following order:

1. A global external function.

2. A global function.

3. An object function and local external function. If the object is a descendant, PowerBuilder
searches upward through the ancestor hierarchy to find a match for the function prototype.

4. A system function.

DataWindow expression functions


The functions that you use in the DataWindow painter in expressions for computed
fields, filters, validation rules, and graphed data cannot be overridden. For example, if
you create a global function called Today, it is used instead of the PowerScript system
function Today, but it is not used instead of the DataWindow expression function
Today.

Qualified function names


You can qualify an object function using dot notation to ensure that the object function
is found, not a global function of the same name. With a qualified name, the search for a
matching function involves the ancestor hierarchy only (item 3 in the search list above), as
shown in the following examples of function calls:

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.

1.6.2.2 Finding events


PowerBuilder events in descendant objects are, by default, extensions of ancestor events.
PowerBuilder searches for events in the object's ancestor hierarchy until it gets to the top
ancestor or finds an event that overrides its ancestor. Then it begins executing the events,
from the ancestor event down to the descendant event.
Finding functions versus events
The following illustration shows the difference between searching for events and searching
for functions:

1.6.3 Triggering versus posting functions and events


Triggering
In PowerBuilder, when you trigger a function or event, it is called immediately. Its return
value is available for use in the script.

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 an operand in an expression

• 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))

TriggerEvent and PostEvent functions


For backward compatibility, the TriggerEvent and PostEvent functions are still
available, but you cannot pass arguments to the called event. You must pass data to
the event in PowerBuilder's Message object.

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 ()

1.6.4 Static versus dynamic calls


Calling functions and events
PowerBuilder calls functions and events in three ways, depending on the type of function or
event and the lookup method defined.

Table 1.36: How PowerBuilder calls functions and events


Type of Compiler typing Comments
function
Global and Strongly typed. The function must These functions must exist and
system functions exist when the script is compiled. are called directly. They are not
polymorphic, and no substitution is
ever made at execution time.
Object functions Strongly typed. The function must The functions are polymorphic. They
with STATIC exist when the script is compiled. must exist when you compile, but
lookup if another class is instantiated at
execution time, its function is called
instead.
Object functions Weakly typed. The function does The functions are polymorphic. The
with DYNAMIC not have to exist when the script is actual function called is determined at
lookup compiled. execution time.

Specifying static or dynamic lookup


For object functions and events, you can choose when PowerBuilder looks for them by
specifying static or dynamic lookup. You specify static or dynamic lookup using the STATIC
or DYNAMIC keywords. The DYNAMIC keyword applies only to functions that are
associated with an object. You cannot call global or system functions dynamically.

1.6.4.1 Static calls


By default, PowerBuilder makes static lookups for functions and events. This means that it
identifies the function or event by matching the name and argument types when it compiles
the code. A matching function or event must exist in the object at compile time.

Page 107
PowerScript Topics

Results of static calls


Static calls do not guarantee that the function or event identified at compile time is the one
that is executed. Suppose that you define a variable of an ancestor type and it has a particular
function definition. If you assign an instance of a descendant object to the variable and the
descendant has a function that overrides the ancestor's function (the one found at compile
time), the function in the descendant is executed.

1.6.4.2 Dynamic calls

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:

• Ancestor window w_a with a function Set(integer).

• 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.

Disadvantages of dynamic calls


Slower performance
Because dynamic calls are resolved at runtime, they are slower than static calls. If you need
the fastest performance, design your application to avoid dynamic calls.
Less error checking
When you use dynamic calls, you are foregoing error checking provided by the compiler.
Your application is more open to application errors, because functions that are called
dynamically might be unavailable at execution time. Do not use a dynamic call when a static
call will suffice.
Example using dynamic call
A sample application has an ancestor window w_datareview_frame that defines several
functions called by the menu items of m_datareview_framemenu. They are empty stubs
with empty scripts so that static calls to the functions will compile. Other windows that are
descendants of w_datareview_frame have scripts for these functions, overriding the ancestor
version.
The wf_print function is one of these -- it has an empty script in the ancestor and appropriate
code in each descendant window:
guo_global_vars.ish_currentsheet.wf_print ()

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()

1.6.4.2.1 Errors when calling functions and events dynamically


If you call a function or event dynamically, different conditions create different results, from
no effect to an execution error. The tables in this section illustrate this.
Functions
The rules for functions are similar to those for events, except functions must exist: if a
function is not found, an error always occurs. Although events can exist without a script, if a
function is defined it has to have code. Consider the following statements:

1. This statement calls a function without looking for a return value:


object.DYNAMIC funcname( )

2. This statement looks for an integer return value:


int li_int
li_int = object.DYNAMIC funcname( )

3. This statement looks for an Any return value:


any la_any
la_any = object.DYNAMIC funcname( )

The following table uses these statements as examples.

Table 1.39: Dynamic function calling errors


Condition 1 Condition 2 Result Example
The function does None. Execution error 65: All the statements
not exist. Dynamic function cause error 65.
not found.
The function is found The code is looking Execution error 63: Statements 2 and 3
and executed but is for a return value. Function/event with cause error 63.
not defined with a no return value used
return value. in expression.

Events
Consider these statements:

1. This statement calls an event without looking for a return value:


object.EVENT DYNAMIC eventname( )

2. This example looks for an integer return value:


int li_int
li_int = object.EVENT DYNAMIC eventname( )

3. This example looks for an Any return value:


any la_any
la_any = object.EVENT DYNAMIC eventname( )

Page 110
PowerScript Topics

The following table uses these statements as examples.

Table 1.40: Dynamic event calling errors


Condition 1 Condition 2 Result Example
The event does The code is not Nothing; the call fails Statement 1 fails but
not exist. looking for a return silently. does not cause an error.
value.
The code is looking A null of the Any La_any is set to null in
for a return value. datatype is returned. statement 3.
If the expected datatype is The assignment to li_int
not Any, execution error causes execution error
19 occurs: Cannot convert 19 in statement 2.
Any in Any variable to
datatype.
The event is The event has a A null of the defined If eventname is defined
found but is not defined return value. datatype is returned. to return integer,
implemented li_int is set to null in
(there is no statement 2.
script).
The event does not A null of the Any La_any is set to null in
have a defined return datatype is returned. statement 3.
value.
If the expected datatype is The assignment to li_int
not Any, execution error causes execution error
19 occurs: Cannot convert 19 in statement 2.
Any in Any variable to
datatype.
The event is The code is looking Execution error 63: Statements 2 and 3
found and for a return value. Function/event with cause error 63.
executed but is no return value used in
not defined with expression.
a return value.

When an error occurs


You can surround a dynamic function call in a try-catch block to prevent the application from
terminating when an execution error occurs. Although you can also handle the error in the
SystemError event, you should not allow the application to continue once the SystemError
event is invoked -- the SystemError event should only clean up and halt the application.
For information on using try-catch blocks, see Section 2.2.9, “Exception handling in
PowerBuilder” in Application Techniques.
If the arguments do not match
Function arguments are part of the function's definition. Therefore, if the arguments do not
match (a compatible match, not an exact match), it is essentially a different function. The
result is the same as if the function did not exist.

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

1.6.5 Overloading, overriding, and extending functions and events


In PowerBuilder, when functions are inherited, you can choose to overload or override the
function definition, described in Overloading and overriding functions.
When events are inherited, the scripts for those events are extended by default. You can
choose to extend or override the script, described in Extending and overriding events.

1.6.5.1 Overloading and overriding functions


To create an overloaded function, you declare the function as you would any function using
Insert>Function.
Overriding means defining a function in a descendant object that has the same name and
argument list as a function in the ancestor object. In the descendant object, the function in
the descendant is always called instead of the one in the ancestor -- unless you use the scope
resolution operator (::).
To override a function, open the descendant object in the painter, select the function in
the Script view, and code the new script. The icon that indicates that there is a script for a
function is half shaded when the function is inherited from an ancestor.
You can overload or override object functions only -- you cannot overload global functions.

1.6.5.1.1 Type promotion when matching arguments for overloaded functions


When you have overloaded a function so that one version handles numeric values and another
version handles strings, it is clear to the programmer what arguments to provide to call each

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))

1.6.5.2 Extending and overriding events


In PowerBuilder, when you write event scripts in a descendant object, you can extend
or override scripts that have been written in the ancestor. Extending (the default) means
executing the ancestor's script first, then executing code in the descendant's event script.
Overriding means ignoring the ancestor's script and only executing the script in the
descendant.

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.

1.6.6 Passing arguments to functions and events


In PowerBuilder, arguments for built-in or user-defined functions and events can be passed
three ways:
Table 1.41: Passing arguments to functions and events
Method of Description
passing
By value A copy of the variable is available in the function or event script. Any changes
to its value affect the copy only. The original variable in the calling script is
not affected.
By A pointer to the variable is passed to the function or event script. Changes
reference affect the original variable in the calling script.
Read-only The variable is available in the function or event. Its value is treated as a
constant changes to the variable are not allowed and cause a compiler error.
Read-only provides a performance advantage for some datatypes because
it does not create a copy of the data, as with by value. Datatypes for which
read-only provides a performance advantage are string, blob, date, time, and
DateTime.
For other datatypes, read-only provides documentation for other developers by
indicating something about the purpose of the argument.

1.6.6.1 Passing objects


When you pass an object to a function or event, the object must exist when you refer to its
properties and functions. If you call the function but the object has been destroyed, you get
the execution error for a null object reference. This is true whether you pass by reference, by
value, or read-only.
To illustrate, suppose you have a window with a SingleLineEdit. If you post a function
in the window's Close event and pass the SingleLineEdit, the object does not exist when
the function executes. To use information from the SingleLineEdit, you must pass the
information itself, such as the object's text, rather than the object. When passing an object,
you never get another copy of the object. By reference and by value affect the object
reference, not the object itself.
Objects passed by value
When you pass an object by value, you pass a copy of the reference to the object. That
reference is still pointing to the original object. If you change properties of the object, you
are changing the original object. However, you can change the value of the variable so that it
points to another object without affecting the original variable.

Page 114
PowerScript Topics

Objects passed by reference


When you pass an object by reference, you pass a pointer to the original reference to the
object. Again, if you change properties of the object, you are changing the original object.
You can change the value of the variable that was passed, but the result is different -- the
original reference now points to the new object.
Objects passed as read-only
When you pass an object as read-only, you get a copy of the reference to the object. You
cannot change the reference to point to a new object (because read-only is equivalent to a
CONSTANT declaration), but you can change properties of the object.

1.6.6.2 Passing structures


Structures as arguments behave like simple variables, not like objects.
Structures passed by value
When you pass a structure by value, PowerBuilder passes a copy of the structure. You can
modify the copy without affecting the original.
Structures passed by reference
When you pass a structure by reference, PowerBuilder passes a reference to the structure.
When you changes values in the structure, you are modifying the original. You will not get a
null object reference, because structures always exist until they go out of scope.
Structures passed as read-only
When you pass a structure as read-only, PowerBuilder passes a copy of the structure. You
cannot modify any members of the structure.

1.6.6.3 Passing arrays


When an argument is an array, you specify brackets as part of the argument name in the
declaration for the function or event.
Variable-size array as an argument
For example, suppose a function named uf_convertarray accepts a variable-size array of
integers. If the argument's name is intarray, then for Name enter intarray[ ] and for Type enter
integer.
In the script that calls the function, you either declare an array variable or use an instance
variable or value that has been passed to you. The declaration of that variable, wherever it is,
looks like this:
integer a[]

When you call the function, omit the brackets, because you are passing the whole array. If
you specified brackets, you would be passing one value from the array:
uf_convertarray(a)

Fixed-size array as an argument


For comparison, suppose the uf_convertarray function accepts a fixed-size array of integers
of 10 elements instead. If the argument's name is intarray, then for Name enter intarray[10],
and for Type enter integer.

Page 115
PowerScript Topics

The declaration of the variable to be passed looks like this:


integer a[10]

You call the function the same way, without brackets:


uf_convertarray(a)

If the array dimensions do not match


If the dimensions of the array variable passed do not match the dimensions declared
for the array argument, then array-to-array assignment rules apply. For more
information, see Declaring arrays.

1.6.7 Using return values


You can use return values of functions and events.

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)

To ignore a return value, call the function as a single statement:


Beep(4) // This returns a value, but it is
// rarely needed.

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.

1.6.7.3 Using cascaded calling and return values


PowerBuilder dot notation allows you to chain together several object function or event calls.
The return value of the function or event becomes the object for the following call.
This syntax shows the relationship between the return values of three cascaded function calls:
func1returnsobject( ).func2returnsobject( ).func3returnsanything( )

Disadvantage of cascaded calls


When you call several functions in a cascade, you cannot check their return values
and make sure they succeeded. If you want to check return values (and checking is
always a good idea), call each function separately and assign the return values to
variables. Then you can use the verified variables in dot notation before the final
function name.

Dynamic calls
If you use the DYNAMIC keyword in a chain of cascaded calls, it carries over to all function
calls that follow.
In this example, both func1 and func2 are called dynamically:
object1.DYNAMIC func1().func2()

The compiler reports an error if you use DYNAMIC more than once in a cascaded call. This
example would cause an error:
object1.DYNAMIC func1().DYNAMIC func2() // error

Posted functions and events


Posted functions and events do not return a value to the calling scripts. Therefore, you can
only use POST for the last function or event in a cascaded call. Calls before the last must
return a valid object that can be used by the following call.
System events
System events can only be last in a cascaded list of calls, because their return value is a long
(or they have no return value). They do not return an object that can be used by the next call.
An event you have defined can have a return value whose datatype is an object. You can
include such events in a cascaded call.

1.6.8 Syntax for calling PowerBuilder functions and events


Description
This syntax is used to call all PowerBuilder functions and events. Depending on the
keywords used, this syntax can be used to call system, global, object, user-defined, and
external functions as well as system and user-defined events.
Syntax

Page 117
PowerScript Topics

{ objectname.} { type } { calltype } { when } name ( { argumentlist } )

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:

• TRIGGER -- (Default) Execute it immediately.

• 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( )

This statement calls the global user-defined function gf_setup_appl:


gf_setup_appl(24, "Window1")

Page 119
PowerScript Topics

This statement calls the system function PrintRect:


PrintRect(job, 250, 250, 7500, 1000, 50)

Example 2
The following statements show calls to global and system functions.
This statement posts the global user-defined function gf_setup_appl. The function is executed
when the calling script finishes:
POST gf_setup_appl(24, "Window1")

This statement posts the system function PrintRect. It is executed when the calling script
finishes. The print job specified in job must still be open:
POST PrintRect(job, 250, 250, 7500, 1000, 50)

Example 3
In a script for a control, these statements call a user-defined function defined in the parent
window. The statements are equivalent, because FUNCTION, STATIC, and TRIGGER are
the defaults:
Parent.FUNCTION STATIC TRIGGER wf_process( )
Parent.wf_process( )

Example 4
This statement in a DataWindow control's Clicked script calls the DoubleClicked event
for the same control. The arguments the system passed to Clicked are passed on to
DoubleClicked. When triggered by the system, PowerBuilder passes DoubleClicked those
same arguments:
This.EVENT DoubleClicked(xpos, ypos, row, dwo)

This statement posts the same event:


This.EVENT POST DoubleClicked(xpos, ypos, row, dwo)

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.

1.6.9 Calling functions and events in an object's ancestor


Description
In PowerBuilder, when an object is instantiated with a descendant object, even if its class is
the ancestor and that descendant has a function or event script that overrides the ancestor's,
the descendant's version is the one that is executed. If you specifically want to execute the

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:

• TRIGGER -- (Default) Execute it immediately

• 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

Overriding event scripts


The AncestorReturnValue variable is only available when you override an event script after
you call the ancestor event using either of these versions of the CALL syntax:
CALL SUPER::event_name
CALL ancestor_name::event_name

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
...

For information about CALL, see CALL.


Examples
Example 1
Suppose a window w_ancestor has an event ue_process. A descendant window has a script
for the same event.
This statement in a script in the descendant searches the event chain and calls all appropriate
events. If the descendant extends the ancestor script, it calls a script for each ancestor in
turn followed by the descendant script. If the descendant overrides the ancestor, it calls the
descendant script only:
EVENT ue_process( )

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 Statements, Events, and Functions


This part provides reference information about each of the components of the PowerScript
language.

2.1 PowerScript Statements


About this chapter
This chapter describes the PowerScript statements and how to use them in scripts.

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 assignments use operator shortcuts:


int i = 4i ++ // i is now 5.
i -- // i is 4 again.
i += 10 // i is now 14.
i /= 2 // i is now 7.

These shortcuts can be used only in pure assignment statements. They cannot be used with
other operators in a statement. For example, the following is invalid:
int i, j
i = 12
j = i ++ // INVALID

The following is valid, because ++ is used by itself in the assignment:


int i, j
i = 12
i ++
j = i

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

Using the standard syntax


For most purposes, you should use the standard syntax for calling functions and
events. For more information about the standard syntax, see Syntax for calling
PowerBuilder functions and events.
The standard syntax allows you to trigger or post an event or function in an ancestor
and then pass arguments, but it does not allow you to call a script for a control in the
ancestor.

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

2.1.3 CHOOSE CASE


Description
A control structure that directs program execution based on the value of a test expression
(usually a variable).
Syntax
CHOOSE CASE testexpression
CASE expressionlist
statementblock
{ CASE expressionlist
statementblock
. . .
CASE expressionlist
statementblock }
CASE ELSE
statementblock }
END CHOOSE

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

• A list of values separated by commas (such as 2, 4, 6, 8)

• A TO clause (such as 1 TO 30)

• IS followed by a relational operator and comparison value (such as


IS>5)

• Any combination of the above with an implied OR between expressions


(such as 1, 3, 5, 7, 9, 27 TO 33, IS >42)

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

Syntax 2 (allows the application to choose the object type dynamically):


objectvariable = CREATE USING objecttypestring

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:

• A standard datatype, such as integer or string

• Any structure, such as the Environment object

• Any object whose AutoInstantiate setting is true

• Any object that has been instantiated using a function, such as Open

Specifying the object type dynamically


CREATE USING allows your application to choose the object type dynamically. It is usually
used to instantiate an ancestor variable with an instance of one of its descendants. The
particular descendant is chosen at execution time.
For example, if uo_a has two descendants, uo_a_desc1 and uo_a_desc2, then the application
can select the object to be created based on current conditions:
uo_a uo_a_var
string ls_objectname

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

Destroying objects you create


When you have finished with an object 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.
Examples
Example 1
These statements create a new transaction object and stores the object in the variable
DBTrans:
transaction DBTrans
DBTrans = CREATE transaction
DBTrans.DBMS = 'ODBC'

Example 2
These statements create a user object when the application has need of the services it
provides. Because the user object 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

If the service object was created, then it also needs to be destroyed:


IF isvalid(invo_service) THEN DESTROY invo_service

Example 3
When you create a DataStore object, you also have to give it a DataObject and call
SetTransObject before you can use it:
l_ds_delete = CREATE u_ds

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")

The window's Close event destroys istg_prod_pic:


integer li_result
li_result = istg_prod_pic.Save( )
IF li_result = 0
THEN
DESTROY istg_prod_pic
END IF

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.

You can nest DO...LOOP control structures.


Syntax
DO UNTIL condition
statementblock
LOOP
DO WHILE condition
statementblock
LOOP
DO
statementblock

Page 133
Statements, Events, and Functions

LOOP UNTIL condition


DO
statementblock
LOOP WHILE condition

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

A variable as the step increment


If you need to use a variable for the step increment, you can use one of the
DO...LOOP constructions and increment the counter yourself within the loop.

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

This GOTO statement skips over the Taxable=FALSE line:


Goto NextStep
Taxable=FALSE //This statement never executes.
NextStep:
Rate=Count/Count4

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

THEN HALT CLOSE

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.

Syntax 2 (the multiline format):


IF condition1 THEN
action1
{ ELSEIF condition2 THEN
action2
. . . }
{ ELSE
action3 }
END IF

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:

• Beep twice if X equals Y

• Display the Parts list box and highlight item 5 if X equals Z

• Display the Choose list box if X is blank

• Hide the Empty button and display the Full button if none of the above conditions is true

IF X=Y THEN
Beep(2)
ELSEIF X=Z THEN
Show (lb_parts); lb_parts.SetState(5,TRUE)
ELSEIF X=" " THEN
Show (lb_choose)
ELSE
Hide(cb_empty)
Show(cb_full)
END IF

2.1.13 RETURN
Description

Page 140
Statements, Events, and Functions

Stops the execution of a script or function immediately.


Syntax
RETURN { expression }

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

where ExceptionType is an object of type Throwable.


If you attempt to throw a noninstantiated exception, you will not get back the exception
information you want, since the only exception information you retrieve will be a
NullObjectError.
In a method script, you can only throw an exception that you declare in the method prototype
or that you handle in a try-catch block. The PowerScript compiler displays an error message
if you try to throw a user-defined exception without declaring it in the prototype Throws
statement and without surrounding it in an appropriate try-catch block.
When a RuntimeError, or a descendant of RuntimeError, is thrown, the instance variable
containing line number information will be filled in at the point where the THROW statement
occurs. If the error is handled and thrown again, this information will not be updated unless it
has specifically been set to null.
Examples
long ll_result
ll_result = myConnection.ConnectToServer()

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

Internal use only.


You do not type or otherwise add the THROWS clause to function calls in a PowerBuilder
script. However, you can add a THROWS clause to any PowerBuilder function or to any user
event that is not defined by a pbm event ID.
For more information about adding a THROWS clause to a function or event prototype, see
Section 3.2.2.6, “Defining a THROWS clause” in Users Guide. For more information about
exception handling, see Section 2.2.9, “Exception handling in PowerBuilder” in Application
Techniques.

2.1.16 TRY...CATCH...FINALLY...END TRY


Description
Isolates code that can cause an exception, describes what to do if an exception of a given type
is encountered, and allows you to close files or network connections (and return objects to
their original state) whether or not an exception is encountered.
Syntax
TRY trystatements
CATCH ( ThrowableType1 exIdentifier1 )
catchstatements1
CATCH ( ThrowableType2 exIdentifier2 )
catchstatements2
...
CATCH ( ThrowableTypeN exIdentifierN )
catchstatementsN
FINALLY
cleanupstatements
END TRY

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.

FINALLY clause restriction


Do not use RETURN statements in the FINALLY clause of a TRY-CATCH block.
This can prevent the exception from being caught by its invoker.

See also
THROW

2.2 SQL Statements


About this chapter
This chapter describes the embedded SQL and dynamic SQL statements and how to use them
in scripts.

2.2.1 Using SQL in scripts


PowerScript supports standard embedded SQL statements and dynamic SQL statements in
scripts. In general, PowerScript supports all DBMS-specific clauses and reserved words that
occur in the supported SQL statements. For example, PowerBuilder supports DBMS-specific
built-in functions within a SELECT command.
For information about embedded SQL, see Chapter 6, Using Embedded SQL in Connecting to
Your Database.
Referencing PowerScript variables in scripts
Wherever constants can be referenced in SQL statements, PowerScript variables preceded
by a colon (:) can be substituted. Any valid PowerScript variable can be used. This INSERT
statement uses a constant value:
INSERT INTO EMPLOYEE ( SALARY ) VALUES ( 18900 ) ;

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

Using indicator variables


PowerBuilder supports indicator variables, which are used to identify null values or
conversion errors after a database retrieval. Indicator variables are integers that are specified
in the HostVariableList of a FETCH or SELECT statement.
Each indicator variable is separated from the variable it is indicating by a space (but no
comma). For example, this statement is a HostVariableList without indicator variables:
:Name, :Address, :City

The same HostVariableList with indicator variables looks like this:


:Name :IndVar1, :Address :IndVar2, :City :IndVar3

Indicator variables have one of these values:


Table 2.17:
Page Meaning
0 Valid, non-null value
-1 Null value
-2 Conversion error

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 )

Error handling in scripts


The scripts shown in the SQL examples above do not include error handling, but it is good
practice to test the success and failure codes (the SQLCode attribute) in the transaction object
after every statement. The codes are:
Table 2.18:
Value Meaning
0 Success.

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

Painting standard SQL


You can paint the following SQL statements in scripts and functions:

• Declarations of SQL cursors and stored procedures

• Cursor FETCH, UPDATE, and DELETE statements

• Noncursor SELECT, INSERT, UPDATE, and DELETE statements

For more information about scope, see Where to declare variables.


You can declare cursors and stored procedures at the scope of global, instance, shared, or
local variables. A cursor or procedure can be declared in the Script view using the Paste SQL
button in the PainterBar.
You can paint standard embedded SQL statements in the Script view, the Function painter,
and the Interactive SQL view in the Database painter using the Paste SQL button in the
PainterBar or the Paste Special>SQL item from the pop-up menu.
Supported SQL statements
In general, all DBMS-specific features are supported in PowerScript if they occur within a
PowerScript-supported SQL statement. For example, PowerScript supports DBMS-specific
built-in functions within a SELECT command.
However, any SQL statement that contains a SELECT clause must also contain a FROM
clause in order for the script to compile successfully. To solve this problem, add a FROM
clause that uses a "dummy" table to SELECT statements without FROM clauses. For
example:
string resselect user_name() into:res from dummy;
select db_name() into:res from dummy;
select date('2001-01-02:21:20:53') into:res from dummy;

Disabling database connection when compiling and building

Page 146
Statements, Events, and Functions

When PowerBuilder compiles an application that contains embedded SQL, it connects to


the database profile last used in order to check for database access errors during the build
process. For applications that use multiple databases, this can result in spurious warnings
during the build since the embedded SQL can be validated only against that single last-
used database and not against the databases actually used by the application. In addition, an
unattended build, such as a lengthy overnight rebuild, can stall if the database connection
cannot be made.
To avoid these issues, you can select the Disable Database Connection When Compiling and
Building check box on the general page of the System Options dialog box.

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.

2.2.1.1 CLOSE Cursor


Description
Closes the SQL cursor CursorName; ends processing of CursorName.
Syntax
CLOSE CursorName ;

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 ;

2.2.1.2 CLOSE Procedure


Description

Page 147
Statements, Events, and Functions

Closes the SQL procedure ProcedureName; ends processing of ProcedureName.

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 ;

2.2.1.5 DECLARE Cursor


Description
Declares a cursor for the specified transaction object.
Syntax
DECLARE CursorName CURSOR FOR SelectStatement
{USING TransactionObject};

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 ;

2.2.1.6 DECLARE Procedure


Description
Declares a procedure for the specified transaction object.

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.

2.2.1.8 DELETE Where Current of Cursor


Description

Page 152
Statements, Events, and Functions

Deletes the row in which the cursor is positioned.

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 ;

2.2.1.13 OPEN Cursor


Description
Causes the SELECT specified when the cursor was declared to be executed.
Syntax
OPEN CursorName ;

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

ROLLBACK USING emp_tran ;

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)

SELECT employee.Emp_LName, employee.Emp_FName


INTO :Emp_lname, :Emp_fname
FROM Employee
WHERE Employee.Emp_nbr = :Emp_num
USING Emp_tran ;

IF Emp_tran.SQLCode = 100 THEN


MessageBox("Employee Inquiry", &
"Employee Not Found")
ELSEIF Emp_tran.SQLCode > 0 then
MessageBox("Database Error", &
Emp_tran.SQLErrText, Exclamation!)
END IF

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 ;

IF Emptran.SQLNRows > 0 THEN


COMMIT USING Emp_tran ;
END IF

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

Updates the rows in TableName in BlobColumn.


Syntax
UPDATEBLOB TableName
SET BlobColumn = BlobVariable
RestOfUpdateStatement {USING TransactionObject} ;

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

IF Emptran.SQLNRows > 0 THEN


COMMIT 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.

2.2.1.19 UPDATE Where Current of Cursor


Description
Updates the row in which the cursor is positioned using the values in SetStatement.
Syntax
UPDATE TableName SetStatement WHERE CURRENT OF CursorName ;

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 ;

2.2.2 Using dynamic SQL


General information
Because database applications usually perform a specific activity, you usually know the
complete SQL statement when you write and compile the script. When PowerBuilder
does not support the statement in embedded SQL (as with a DDL statement) or when the
parameters or the format of the statements are unknown at compile time, the application must
build the SQL statements at runtime. This is called dynamic SQL. The parameters used in
dynamic SQL statements can change each time the program is executed.

Using SQL Anywhere


For information about using dynamic SQL with SQL Anywhere, see the SQL
Anywhere documentation.

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

• To handle these situations, you use:

• The PowerBuilder dynamic SQL statements

• The dynamic versions of CLOSE, DECLARE, FETCH, OPEN, and EXECUTE

• The PowerBuilder datatypes DynamicStagingArea and DynamicDescriptionArea

About the examples


The examples assume that the default transaction object (SQLCA) has been assigned
valid values and that a successful CONNECT has been executed. Although the
examples do not show error checking, you should check the SQLCode after each SQL
statement.

Dynamic SQL statements


The PowerBuilder dynamic SQL statements are:
DESCRIBE DynamicStagingArea
INTO DynamicDescriptionArea ;EXECUTE {IMMEDIATE} SQLStatement
{USING TransactionObject} ;EXECUTE DynamicStagingArea
USING ParameterList ;EXECUTE DYNAMIC Cursor | Procedure
USING ParameterList ;OPEN DYNAMIC Cursor | Procedure
USING ParameterList ;EXECUTE DYNAMIC Cursor | Procedure
USING DESCRIPTOR DynamicDescriptionArea ;OPEN DYNAMIC Cursor | Procedure
USING DESCRIPTOR DynamicDescriptionArea ;PREPARE DynamicStagingArea
FROM SQLStatement {USING TransactionObject} ;

Two 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

After the EXECUTE statement is completed, SQLSA is no longer referenced.


DynamicDescriptionArea
DynamicDescriptionArea is a PowerBuilder datatype. PowerBuilder uses a variable of this
type to store information about the input and output parameters used in Format 4 of dynamic
SQL.
PowerBuilder provides a global DynamicDescriptionArea named SQLDA that you can use
when you need a DynamicDescriptionArea variable.
If necessary, you can declare and create additional object variables of the type
DynamicDescriptionArea. These statements declare and create the variable, which must be
done before referring to it in a dynamic SQL statement:
DynamicDescriptionArea dda_desc1
dda_desc1 = CREATE DynamicDescriptionArea

For more information about SQLDA, see Dynamic SQL Format 4.


Preparing to use dynamic SQL
When you use dynamic SQL, you must:

• Prepare the DynamicStagingArea in all formats except Format 1

• Describe the DynamicDescriptionArea in Format 4

• Execute the statements in the appropriate order

Preparing and describing the datatypes


Since the SQLSA staging area is the only connection between the execution of a SQL
statement and a transaction object, an execution error will occur if you do not prepare the
SQL statement correctly.
In addition to SQLSA and SQLDA, you can declare other variables of the
DynamicStagingArea and DynamicDescriptionArea datatypes. However, this is required
only when your script requires simultaneous access to two or more dynamically prepared
statements.
This is a valid dynamic cursor:
DECLARE my_cursor DYNAMIC CURSOR FOR SQLSA ;PREPARE SQLSA FROM "SELECT emp_id FROM
employee" ;OPEN DYNAMIC my_cursor ;

This is an invalid dynamic cursor. There is no PREPARE, and therefore an execution error
will occur:
DECLARE my_cursor DYNAMIC CURSOR FOR SQLSA ;OPEN DYNAMIC my_cursor ;

Statement order

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

2. The OPEN in Formats 3 and 4 before the FETCH

3. The CLOSE at the end

If you have multiple PREPARE statements, the order affects the contents of SQLSA.
These statements illustrate the correct ordering:
DECLARE my_cursor DYNAMIC CURSOR FOR SQLSA
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.

Declaring a procedure with the SQL Native Client database interface


When you connect to Microsoft SQL Server using the PowerBuilder SQL Native Client
(SNC) database interface, the syntax for declaring a procedure is:
DECLARE logical_procedure_name PROCEDURE FOR
[@rc=]procedure_name
{@param1 = value1 [OUTPUT], @param2 = value2 [OUTPUT], ...}
{USING transaction_object};

[@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.

2.2.2.1 Dynamic SQL Format 1


Description
Use this format to execute a SQL statement that does not produce a result set and does not
require input parameters. You can use this format to execute all forms of Data Definition
Language (DDL).
Syntax

Page 165
Statements, Events, and Functions

EXECUTE IMMEDIATE SQLStatement {USING TransactionObject} ;

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.

For SAP ASE users


If you are connected to an ASE database, set AUTOCOMMIT to true before
executing the CREATE.

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 ;

2.2.2.2 Dynamic SQL Format 2


Description
Use this format to execute a SQL statement that does not produce a result set but does require
input parameters. You can use this format to execute all forms of Data Definition Language
(DDL).
Syntax
PREPARE DynamicStagingArea FROM SQLStatement
{USING TransactionObject} ;
EXECUTE DynamicStagingArea USING {ParameterList} ;

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 ;

2.2.2.3 Dynamic SQL Format 3


Description
Use this format to execute a SQL statement that produces a result set in which the input
parameters and result set columns are known at compile time.
Syntax
DECLARE Cursor | Procedure
DYNAMIC CURSOR | PROCEDURE
FOR DynamicStagingArea ;
PREPARE DynamicStagingArea FROM SQLStatement
{USING TransactionObject} ;
OPEN DYNAMIC Cursor
{USING ParameterList} ;
EXECUTE DYNAMIC Procedure
{USING ParameterList} ;
FETCH Cursor | Procedure

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

PREPARE SQLSA FROM "SELECT emp_id FROM employee" ;


OPEN DYNAMIC my_cursor ;
FETCH my_cursor INTO :Emp_id_var ;
CLOSE my_cursor ;

You can loop through the cursor as you can in embedded static SQL.
Example 2
These statements associate a cursor named my_cursor with SQLSA, prepare a SELECT
statement with one parameter in SQLSA, open the cursor, and substitute the value of the
variable Emp_state_var for the parameter in the SELECT statement. The employee ID in the
active row is returned into the PowerBuilder variable Emp_id_var:
DECLARE my_cursor DYNAMIC CURSOR FOR SQLSA ;
integer Emp_id_var
string Emp_state_var = "MA"
string sqlstatement

sqlstatement = "SELECT emp_id FROM employee "&


+"WHERE state = ?"
PREPARE SQLSA FROM :sqlstatement ;
OPEN DYNAMIC my_cursor using :Emp_state_var ;
FETCH my_cursor INTO :Emp_id_var ;
CLOSE my_cursor ;

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

PREPARE SQLSA FROM "execute emp_select @stateparm=?" ;


Emp_state_var = "MA"
EXECUTE DYNAMIC my_proc USING :Emp_state_var ;
FETCH my_proc INTO :Emp_id_var ;
CLOSE my_proc ;

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 ;

EXECUTE DYNAMIC my_proc USING :var1, :var2 ;

//fetch result set


. . .

//fetch return value and output parameter


FETCH my_proc INTO : ReturnVal, :var2;

CLOSE my_proc ;

Page 169
Statements, Events, and Functions

2.2.2.4 Dynamic SQL Format 4


Description
Use this format to execute a SQL statement that produces a result set in which the number of
input parameters, or the number of result-set columns, or both, are unknown at compile time.
Syntax
DECLARE Cursor | Procedure
DYNAMIC CURSOR | PROCEDURE
FOR DynamicStagingArea ;
PREPARE DynamicStagingArea FROM SQLStatement
{USING TransactionObject} ;
DESCRIBE DynamicStagingArea
INTO DynamicDescriptionArea ;
OPEN DYNAMIC Cursor
USING DESCRIPTOR DynamicDescriptionArea ;
EXECUTE DYNAMIC Procedure
USING DESCRIPTOR DynamicDescriptionArea ;
FETCH Cursor | Procedure
USING DESCRIPTOR DynamicDescriptionArea ;
CLOSE Cursor | Procedure ;

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

Setting and accessing parameter values


The array of input parameter values and the array of output parameter values are also
available. You can use the SetDynamicParm function to set the values of an input parameter
and the following functions to obtain the value of an output parameter:

Table 2.44:
GetDynamicDate GetDynamicNumber
GetDynamicDateTime GetDynamicString
GetDynamicDecimal GetDynamicTime

For information about these functions, see


GetDynamicDate
GetDynamicDateTime
GetDynamicDecimal
GetDynamicNumber
GetDynamicString
GetDynamicTime.
Parameter values
The following enumerated datatypes are the valid values for the input and output parameter
types:

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 ;

DESCRIBE SQLSA INTO SQLDA ;

// If the DESCRIBE is successful, the input


// descriptor array will contain one input
// descriptor that you must fill prior to the OPEN

DECLARE my_cursor DYNAMIC CURSOR FOR SQLSA ;


SetDynamicParm(SQLDA, 1, "MA")

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
// as in the first example.

// To test and see the values:


sValue = SQLDA.GetDynamicString(1)
//messagebox("",sValue)
sValue = SQLDA.GetDynamicString(2)
//messagebox("",sValue)
Do While sqlca.sqlcode <> 100
FETCH my_cursor USING DESCRIPTOR SQLDA ;
sValue = SQLDA.GetDynamicString(1)
//messagebox("",sValue)
sValue = SQLDA.GetDynamicString(2)
//messagebox("",sValue)
Loop

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 ";

DESCRIBE SQLSA INTO SQLDA ;

Page 173
Statements, Events, and Functions

DECLARE my_proc DYNAMIC PROCEDURE FOR SQLSA ;

SetDynamicParm(SQLDA, 1, var1)
SetDynamicParm(SQLDA, 2, var2)

EXECUTE DYNAMIC my_proc USING DESCRIPTOR SQLDA ;

//fetch result set


. . .

//fetch return value and output parameter


FETCH my_proc USING DESCRIPTOR SQLDA ;

//get return value


CHOOSE CASE SQLDA.OutParmType[1]
CASE TypeInteger!
rc = GetDynamicNumber(SQLDA, 1)
CASE TypeLong!
rc = GetDynamicNumber(SQLDA, 1)
CASE TypeString!
Var2 = GetDynamicString(SQLDA, 1)
END CHOOSE

//get output value

CHOOSE CASE SQLDA.OutParmType[2]


CASE TypeString!
Var2 = GetDynamicString(SQLDA, 2)
CASE TypeInteger!
rc = GetDynamicNumber(SQLDA, 2)
CASE TypeLong!
rc = GetDynamicNumber(SQLDA, 2)
END CHOOSE

CLOSE my_proc ;

2.3 PowerScript Events


About this chapter
This chapter discusses events in general and then documents the arguments, event IDs, and
return codes for the events defined for all PowerBuilder controls and objects except the
DataWindow and DataStore. Usage notes and examples provide information about what is
typically done in an event's script.
For information about DataWindow and DataStore events, see Part I, “DataWindow
Reference”.
Contents
The events are listed in alphabetical order.

2.3.1 About events


In PowerBuilder, there are several types of events.
Table 2.46: PowerBuilder event types
Type Occurs in response to
System events with an ID User actions or other system messages or a
call in your scripts

Page 174
Statements, Events, and Functions

Type Occurs in response to


System events without an ID PowerBuilder messages or a call in your
scripts
User-defined events with an ID User actions or other system messages or a
call in your scripts
User-defined events without an ID A call in your scripts

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.

Calling events without specifying their arguments


If you use the CALL statement, you can trigger a system event without specifying its
arguments. However, CALL is obsolete and you should not use it in new applications
except as described in CALL.

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

2.3.5.1 Syntax 1: For ListView controls


Description
Occurs when the user presses the left mouse button in the ListView control and begins
dragging.
Event ID

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)

// To copy, rather than move, omit these two lines


This.DeleteItem(This.SelectedIndex())
This.Arrange()

This code is in the DragDrop event of the target ListView:


This.AddItem(ilvi_dragged_object)
This.Arrange()

See also
BeginRightDrag
DragDrop
DragEnter
DragLeave
DragWithin

Page 180
Statements, Events, and Functions

2.3.5.2 Syntax 2: For TreeView controls


Description
Occurs when the user presses the left mouse button on a label in the TreeView control and
begins dragging.
Event ID

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.

The user cannot drag a highlighted item.


Dragging a TreeView item onto another control causes the control's standard drag events
(DragDrop, DragEnter, DragLeave, and DragWithin) to occur. The standard drag events
occur for TreeView when another control is dragged within the borders of the TreeView.
Examples
This example moves the first TreeView item in the source TreeView to another TreeView
when the user drags there. itvi_dragged_object is a window instance variable whose type is
TreeViewItem. To copy the item, omit the code that deletes it from the source TreeView.
This code is in the BeginDrag event script of the source TreeView:
long itemnum

// If the TreeView's DragAuto property is FALSE


This.Drag(Begin!)
itemnum = 1
This.GetItem(itemnum, itvi_dragged_object)

Page 181
Statements, Events, and Functions

// To copy, rather than move, omit these two lines


This.DeleteItem(itemnum)
This.SetRedraw(TRUE)

This code is in the DragDrop event of the target TreeView:


This.InsertItemLast(0, itvi_dragged_object)
This.SetRedraw(TRUE)

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

2.3.6.1 Syntax 1: For ListView controls


Description
Occurs when the user clicks on the label of an item after selecting the item.
Event ID

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

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 event to display the name of the ListView item being
edited:
ListViewItem lvi
This.GetItem(index lvi)
sle_info.text = "Editing " + string(lvi.label)

See also
EndLabelEdit

2.3.6.2 Syntax 2: For TreeView controls


Description
Occurs when the user clicks on the label of an item after selecting the item.
Event ID

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

2.3.8.1 Syntax 1: For ListView controls


Description
Occurs when the user presses the right mouse button in the ListView control and begins
dragging.
Event ID

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

2.3.8.2 Syntax 2: For TreeView controls


Description
Occurs when the user presses the right mouse button in the TreeView control and begins
dragging.
Event ID

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"

if MessageBox('server certificate error', strMessage, Question!, YesNo! ) = 1 then


// Continue browsing the web page
Ln_Result = 0
else
// Cancel browsing the web page
Ln_Result = 1
end if

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.

2.3.16.1 Syntax 1: For menus


Description
Occurs when the user chooses an item on a menu.
Event ID

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

2.3.16.2 Syntax 2: For ListView and Toolbar controls


Description
Occurs when the user clicks within the ListView control, either on an item or in the blank
space around items.
Event ID

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.

Using the ItemActivate event for ListView controls


You can use the ItemActivate event (with the OneClickActivate property set to true)
instead of the Clicked event for ListView controls.

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

2.3.16.3 Syntax 3: For Tab controls


Description
Occurs when the user clicks on the tab portion of a Tab control.
Event ID
Table 2.85:
Event ID Objects
pbm_tcnclicked Tab

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

2.3.16.4 Syntax 4: For TreeView controls


Description
Occurs when the user clicks an item in a TreeView control.
Event ID

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

2.3.16.5 Syntax 5: For windows and progress bars


Description

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:

• 1 -- Left mouse button

• 2 -- Right mouse button (windows only)

• 4 -- Shift key

• 8 -- Ctrl key

• 16 -- Middle mouse button (windows only)

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

2.3.16.6 Syntax 6: For Ribbon controls


Description
This is a user event which occurs when the user clicks on an item within a RibbonBar control.
Make sure the parameter (quantities and types) of the user event is correctly defined
according to the requirement of the ribbon control.
Applies to
Ribbon controls (including RibbonTabButtonItem, RibbonLargeButtonItem,
RibbonSmallButtonItem, RibbonCheckBoxItem, and RibbonMenuItem)
Arguments for RibbonTabButtonItem, RibbonLargeButtonItem,
RibbonSmallButtonItem, RibbonCheckBoxItem

Table 2.91:
Argument Description
ItemHandle Long. The handle of the item.

Arguments for RibbonMenuItem (of Normal(0) type)

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

Arguments for RibbonMenuItem (of Recent(2) type)


Table 2.93:
Argument Description
ItemHandle Long. The handle of the button the menu is associated with.
Index Long. The index of the menu item clicked.

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"

//Ue_TabButtonClicked user event must have a long parameter for receiving


//the handle of TabButton where the mouse is clicking, as below
event type long ue_tabbuttonclicked(long itemhandle);
RibbonTabButtonItem lr_TabButton
rbb_1.GetTabButton(ItemHandle,lr_TabButton)
//...
Return 1
end event

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

li_Return = rbb_1.GetMenuByButtonHandle (ItemHandle, lr_Menu)


If li_Return = 1 Then
If SubIndex = 0 Then
li_Return = lr_Menu.GetItem (Index, lr_MenuItem)
//...
Else
li_Return = lr_Menu.GetItem (Index, SubIndex, lr_MenuItem)
//...
End If
Else
Return 0
End If

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

li_Return = rbb_1.GetMenuByButtonHandle(ItemHandle, lr_Menu)


If li_Return = 1 Then
If SubIndex = 0 Then
li_Return = lr_Menu.GetMasterItem(Index, lr_MenuItem)
//...
Else
li_Return = lr_Menu.GetMasterItem(Index,SubIndex, lr_MenuItem)
//...
End If
Else
Return 0
End If

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

2.3.16.7 Syntax 7: For other controls


Description
Occurs when the user clicks on the control.
Event ID

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

2.3.17.1 Syntax 1: For the application object


Description
Occurs when the user closes the application.
Event ID

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

2.3.17.2 Syntax 2: For OLE controls


Description
Occurs when the object in an OLE control has been activated offsite (the OLE server displays
the object in the server's window) and that server is closed.
Event ID

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

2.3.17.3 Syntax 3: For windows


Description
Occurs just before a window is removed from display.
Event ID

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

// Accept the last data entered into the datawindow


dw_1.AcceptText()

//Check to see if any data has changed


IF dw_1.DeletedCount()+dw_1.ModifiedCount() > 0 THEN
li_rc = MessageBox("Closing", &
"Update your changes?", Question!, &
YesNoCancel!, 3)

//User chose to up data and close window

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 chose to close window without updating


ELSEIF li_rc = 2 THEN
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)

CHOOSE CASE la_align


CASE Right!
rb_right.Checked = TRUE
ls_align = "Right!"

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

sle_info.Text = String(column) &


+ " " + ls_label &
+ " " + ls_align &
+ " " + String(li_width)

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:

• Global variables when the system starts up

• Shared variables when the object with the shared variables is loaded

• Instance variables when the object with the instance variables is created

• Local variables when the function that declares them begins executing

Examples
This example retrieves data for the DataWindow dw_1 before its window is displayed:
dw_1.SetTransObject(SQLCA)
dw_1.Retrieve( )

See also
Destructor
Open

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

li_ret = GetSelectedDate( dt_selected)


ls_date = string(dt_selected)
sle_2.text = 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

• "Database statement must refer to blob


variable"

Use with embedded SQL


By default, whenever an error occurs in the Transaction object, the DBError event is called.
The error code and error message are passed to this event. You can add code to the DBError
event to handle these errors.
Use with DataWindow/DataStore
When using a Transaction object with a DataWindow, the DataWindow DBError event
is triggered before the DBError event of the Transaction object. The return value for the
DataWindow DBError event is used to indicate whether the Transaction object's DBError
event should be triggered in turn. When the return value of the DataWindow DBError event
is 0 or 1, the Transaction object's DBError event is also triggered if it is defined. When the
return value of the DataWindow DBError event is 2 or 3, the Transaction object's DBError
event is ignored.
Examples
The following code in the DBError event displays the error message and the SQL statement
sent to the DBMS when a transaction error occurs:
Messagebox("Transaction error","Error message: "&
+sqlerrortext + "~r~n Occurred for this statement:"&
+sqlsyntax)

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:

• DBServerDown! = 1. The server has been shut down. This notification


type is used only by the O10 (Oracle 10g) database interface.

• DBFailover! = 2. The database client is failing over.

• DBDataTruncate! = 3. Data has been truncated.

DBServerDown! is used for Oracle RAC database HA events.


DBFailover! and DBDataTruncate! can be used with other databases for
failover and data truncation warnings.
command A string that informs users which command was being executed when the
notification occurred.
dbmessage A string that describes the reason why the event occurred.

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

2.3.30.1 Syntax 1: For ListView controls


Description
Occurs when an item is deleted.
Event ID

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

2.3.30.2 Syntax 2: For TreeView controls


Description
Occurs when an item is deleted.
Event ID
Table 2.119:
Event ID Objects
pbm_tvndeleteitem TreeView

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.

2.3.34.1 Syntax 1: For ListBox, PictureListBox, ListView, and Tab controls


Description
Occurs when the user double-clicks on the control.
Event ID

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

2.3.34.2 Syntax 2: For TreeView controls


Description
Occurs when the user double-clicks on the control.
Event ID

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

2.3.34.3 Syntax 3: For windows


Description
Occurs when the user double-clicks in an unoccupied area of the window (any area with no
visible, enabled object).
Event ID

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:

• 1 -- Left mouse button

• 2 -- Right mouse button

• 4 -- Shift key

• 8 -- Ctrl key

• 16 -- Middle mouse button

In the Clicked event, the left mouse button is being released, so 1 is not
summed in the value of flags.
For an explanation of flags, see Syntax 2 of MouseMove.

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

2.3.34.4 Syntax 4: For other controls


Description
Occurs when the user double-clicks on the control.
Event ID

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

Return code choices (specify in a RETURN statement):


0 -- Continue processing
Usage
The DoubleClicked event for DropDownListBoxes is only active when the Always Show
List property is on.
See also
Clicked
RButtonDown

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.

2.3.37.1 Syntax 1: For ListBox, PictureListBox, ListView, and Tab controls


Description
Occurs when the user drags an object onto the control and releases the mouse button to drop
the object.
Event ID

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

2.3.37.2 Syntax 2: For TreeView controls


Description
Occurs when the user drags an object onto the control and releases the mouse button to drop
the object.
Event ID

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

2.3.37.3 Syntax 3: For windows and other controls


Description
Occurs when the user drags an object onto the control and releases the mouse button to drop
the object.
Event ID

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( )

// Save the row's status flag for later use


ldwis_delrow = dw_orddetail.GetItemStatus &
(ll_currow, 0, Primary!)

// Now, delete the current row from dw_orddetail


dw_orddetail.DeleteRow(0)

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

IF source.TypeOf() = DataWindow! THEN

ldw_Source = source
ll_RowToDelete = ldw_Source.GetRow()

IF ll_RowToDelete > 0 THEN


li_Choice = MessageBox("Delete", &
"Delete this row?", Question!, YesNo!, 2)
IF li_Choice = 1 THEN
ldw_Source.DeleteRow(ll_RowToDelete)
END IF
ELSE
Beep(1)
END IF

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

2.3.40.1 Syntax 1: For ListBox, PictureListBox, ListView, and Tab controls


Description
Occurs when the user is dragging an object within the control.
Event ID

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

2.3.40.2 Syntax 2: For TreeView controls


Description
Occurs when the user is dragging an object within the control.

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

2.3.40.3 Syntax 3: For windows and other controls


Description
Occurs when the user is dragging an object within the control.
Event ID
Table 2.153:
Event ID Objects
pbm_bndragwithinCheckBox, CommandButton, Graph, InkEdit, InkPicture, Picture,
PictureHyperLink, PictureButton, RadioButton
pbm_cbndragwithin
DropDownListBox, DropDownPictureListBox

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

2.3.43.1 Syntax 1: For ListView controls


Description
Occurs when the user finishes editing an item's label.
Event ID

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

2.3.43.2 Syntax 2: For TreeView controls


Description
Occurs when the user finishes editing an item's label.
Event ID

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

2.3.47.1 Syntax 1: for Connection, DataWindow, DataStore, OLE, OLEObject, OLETxnObject


Description
Occurs when an error is found in a data or property expression for an external object or a
DataWindow object.

Improved error-handling capability in PowerBuilder


The Error event is maintained for backward compatibility. If you do not script the
Error event or change its action argument, information from this event is passed to

Page 239
Statements, Events, and Functions

RuntimeError objects, such as DWRuntimeError or OLERuntimeError. You can


handle these errors in a try-catch block.

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:

• ExceptionFail! -- fail as if this script were not implemented. The


error condition triggers any active event handlers, or if none, the
SystemError event.

• ExceptionIgnore! -- ignore this error and return as if no error occurred


(use this option with caution because the conditions that caused the
error can cause another error).

• ExceptionRetry! -- execute the function or evaluate the expression


again in case the OLE server was not ready. This option is not valid for
DataWindows.

• ExceptionSubstituteReturnValue! -- use the value specified in the


returnvalue argument instead of the value returned by the OLE server
or DataWindow, and cancel the error condition.
returnvalue Any by reference (a value whose datatype matches the expected value
that the OLE server or DataWindow would have returned).
This value is used when the value of action is
ExceptionSubstituteReturnValue!.

Return Values

Page 240
Statements, Events, and Functions

None. Do not use a RETURN statement.


Usage
DataWindow and OLE objects are dynamic. Expressions that use dot notation to refer to data
and properties of these objects might be valid under some runtime conditions but not others.
The Error event allows you to respond to this dynamic situation with error recovery logic.
The Error event also allows you to respond to communications errors in the client component
of a distributed application. In the Error event for a custom connection object, you can tell
PowerBuilder what action to take when an error occurs during communications between the
client and the server.
The Error event gives you an opportunity to substitute a default value when the error is
not critical to your application. Its arguments also provide information that is helpful in
debugging. For example, the arguments can help you debug DataWindow data expressions
that cannot be checked by the compiler -- such expressions can only be evaluated at runtime.

When to substitute a return value


The ExceptionSubstituteReturnValue! action allows you to substitute a return value
when the last element of an expression causes an error. Do not use it to substitute
a return value when an element in the middle of an expression causes an error.
The substituted return value does not match the datatype of the unresolved object
reference and causes a system error.

The ExceptionSubstituteReturnValue! action can be useful for handling errors in data


expressions.
For DataWindows, when an error occurs while evaluating a data or property expression, error
processing occurs like this:

1. The Error event occurs.

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

2.3.47.2 Syntax 2: for CompressorObject objects


Description
Occurs when an error is found in the file compression operation.
Event ID

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

2.3.47.3 Syntax 3: for ExtractorObject objects


Description
Occurs when an error is found in the archive extraction operation.
Event ID

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

If Len(Result) > 0 Then


lnv_JsonParser = Create JsonParser
lnv_JsonParser.LoadString(result)
ll_RootObject = lnv_JsonParser.GetRootItem()
ls_Type = lnv_JsonParser.GetItemString(ll_RootObject, "type")
If IsValid(lnv_JsonParser) Then Destroy (lnv_JsonParser)
End If

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.

Improved error-handling capability in PowerBuilder


The ExternalException event is maintained for backward compatibility. If you do not
script this event or change its action argument, information from this event is passed
to RuntimeError objects, such as OLERuntimeError. You can handle these errors in a
try-catch block.

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:

• ExceptionFail! -- fail as if this script were not implemented. The error


condition triggers the SystemError event.

• ExceptionIgnore! -- ignore this error and return as if no error occurred


(use this option with caution because the conditions that caused the
error can cause another error).

• ExceptionRetry! -- execute the function or evaluate the expression


again in case the OLE server was not ready.

• ExceptionSubstituteReturnValue! -- use the value specified in the


returnvalue argument instead of the value returned by the OLE server
or DataWindow and cancel the error condition.
returnvalue Any by reference.
A value whose datatype matches the expected value that the OLE server
would have returned. This value is used when the value of action is
ExceptionSubstituteReturnValue!.

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:

1. The ExternalException event occurs.

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

// Command line switch for WinHelp numeric context ID


ls_context = "-n " + String(helpcontext)
If Len(HelpFile) > 0 THEN
Run("winhelp.exe " + ls_context + " " + helpfile)
END IF

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

Return code choices (specified in a RETURN statement):


0 -- Continue processing
1 -- Saving of document is canceled
Usage
The SaveDocument function can trigger the FileExists event.
Examples
This script for FileExists checks a flag to see if the user is performing a save (which will
automatically overwrite the opened file) or wants to rename the file using Save As. For the
Save As case, the script asks the user to confirm overwriting the file:
integer li_answer

// If user asked to Save to same file,


// do not prompt for overwriting
IF ib_saveas = FALSE THEN RETURN 0

li_answer = MessageBox("FileExists", &


filename + " already exists. Overwrite?", &
Exclamation!, YesNo!)
MessageBox("Filename arg", filename)

// Returning a non-zero value cancels save


IF li_answer = 2 THEN RETURN 1

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

Gesture name Argument value Mouse action


Double Tap 2 Left Double Click

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( )

This code is in the ue_select user event:


This.SelectText(1, Len(This.Text))

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)

In the Idle event itself, this statement closes the application:


HALT CLOSE

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

Occurs just before a ListView changes.


Event ID

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)

CHOOSE CASE l_tvi.Level


CASE 1
l_tvi.PictureIndex = 1
l_tvi.SelectedPictureIndex = 1
CASE 2
l_tvi.PictureIndex = 2
l_tvi.SelectedPictureIndex = 2
CASE 3
l_tvi.PictureIndex = 3
l_tvi.SelectedPictureIndex = 3
CASE 4
l_tvi.PictureIndex = 4
l_tvi.SelectedPictureIndex = 4
END CHOOSE
This.SetItem(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)

CHOOSE CASE l_tvi.level


CASE 1
l_tvi.PictureIndex = 1
l_tvi.SelectedPictureIndex = 1
CASE 2
l_tvi.PictureIndex = 2
l_tvi.SelectedPictureIndex = 2
CASE 3
l_tvi.PictureIndex = 3
l_tvi.SelectedPictureIndex = 3
CASE 4
l_tvi.PictureIndex = 4
l_tvi.SelectedPictureIndex = 4
END CHOOSE

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)

CHOOSE CASE l_tvi.Level


CASE 1
l_tvi.PictureIndex = 5
l_tvi.SelectedPictureIndex = 1
CASE 2
l_tvi.PictureIndex = 5
l_tvi.SelectedPictureIndex = 2
CASE 3
l_tvi.PictureIndex = 5
l_tvi.SelectedPictureIndex = 3
CASE 4
l_tvi.PictureIndex = 4
l_tvi.SelectedPictureIndex = 5
END CHOOSE
This.SetItem(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

1 -- Prevents the TreeView from expanding


Usage
The ItemExpanding event occurs before the ItemExpanded event.
Examples
This example sets the picture and selected picture for the expanding item:
TreeViewItem l_tvi
integer li_level

This.GetItem(handle, l_tvi)

CHOOSE CASE l_tvi.Level


CASE 1
l_tvi.PictureIndex = 5
l_tvi.SelectedPictureIndex = 1
CASE 2
l_tvi.PictureIndex = 5
l_tvi.SelectedPictureIndex = 2
CASE 3
l_tvi.PictureIndex = 5
l_tvi.SelectedPictureIndex = 3
CASE 4
l_tvi.PictureIndex = 4
l_tvi.SelectedPictureIndex = 5
END CHOOSE

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

This line displays the value of keyflags when a key is pressed.


st_1.Text = String(keyflags)

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

st_1.Text = "LineDown " + String(This.Position)

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

IF This.Position < This.MinPosition + 1 THEN


This.Position = MinPosition
ELSE
This.Position = This.Position - 1
END IF

st_1.Text = "LineLeft " + String(This.Position)

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

st_1.Text = "LineRight " + String(This.Position)

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

st_1.Text = "LineUp " + String(This.Position)

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 statement in ue_accept calls the AcceptText function:


dw_emp.AcceptText( )

This script for the LoseFocus event of a RichTextEdit control performs processing when the
control actually loses focus:
GraphicObject l_control

// Check whether the RichTextEdit still has focus


l_control = GetFocus()
IF TypeOf(l_control) = RichTextEdit! THEN RETURN 0

// Perform processing only if RichTextEdit lost focus


...

This script gets the name of the control instead:


GraphicObject l_control
string ls_name
l_control = GetFocus()
ls_name = l_control.Classname( )

See also
GetFocus

2.3.77 Modified

2.3.77.1 Syntax 1: For Ribbon controls


Description

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

2.3.77.2 Syntax 2: For all other controls


Description
Occurs when the contents in the control have changed.
Event ID

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

2.3.78.1 Syntax 1: For RichTextEdit controls


Description
Occurs when the user presses the left mouse button on the RichTextEdit control.
Event ID

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

2.3.78.2 Syntax 2: For windows


Description

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:

• 1 -- Left mouse button

• 2 -- Right mouse button

• 4 -- Shift key

• 8 -- Ctrl key

• 16 -- Middle mouse button

In the MouseDown event, the left mouse button is always down, so 1


is always summed in the value of flags. For an explanation of flags, see
Syntax 2 of MouseMove.
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
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

2.3.79.1 Syntax 1: For RichTextEdit controls


Description
Occurs when the mouse has moved within the RichTextEdit control.
Event ID

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

2.3.79.2 Syntax 2: For windows


Description
Occurs when the pointer is moved within the window.
Event ID

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:

• 1 -- Left mouse button

• 2 -- Right mouse button

• 4 -- Shift key

• 8 -- Ctrl key

• 16 -- Middle mouse button

Flags is the sum of all the buttons and keys that are pressed.
xpos Integer by value (the distance of the pointer from the left edge of the
window's workspace in pixels).
ypos Integer by value (the distance of the pointer from the top of the window's
workspace in pixels).

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

IF li_flags > 3 THEN


// Shift key is pressed
lb_Shift_key = TRUE
li_flags = li_flags - 4
END IF

IF li_flags > 1 THEN


// Right button is pressed
lb_lb_right_button = TRUE
li_flags = li_flags - 2
END IF

IF li_flags = 1 THEN lb_left_button = TRUE

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

// Ranges for monitor-type control


ld_gaugemax = ocxitem.Object.MaxValue
ld_gaugemin = ocxitem.Object.MinValue
ld_gaugerange = ld_gaugemax - ld_gaugemin

// Horizontal position of mouse within window


ld_value = data * ld_gaugerange / range + ld_gaugemin

// 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

2.3.80.1 Syntax 1: For RichTextEdit controls


Description
Occurs when the user releases the left mouse button in a RichTextEdit control.
Event ID
Table 2.235:
Event ID Objects
pbm_renlbuttonup RichTextEdit

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

2.3.80.2 Syntax 2: For windows


Description
Occurs when the user releases the left mouse button in an unoccupied area of the window
(any area with no visible enabled object).
Event ID

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:

• 1 -- Left mouse button

• 2 -- Right mouse button

• 4 -- Shift key

• 8 -- Ctrl key

• 16 -- Middle mouse button

In the MouseUp event, the left mouse button is being released, so 1 is not
summed in the value of flags. For an explanation of flags, see Syntax 2 of
MouseMove.

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

2.3.87.1 Syntax 1: For the application object


Description
Occurs when the user starts the application.
Event ID

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

SQLCA.Database = ProfileString("myapp.ini", &


"database", "database", "")
SQLCA.Userid = ProfileString("myapp.ini", "database", &
"userid", "")
SQLCA.DBPass = ProfileString("myapp.ini", "database", &
"dbpass", "")
SQLCA.Logid = ProfileString("myapp.ini", "database", &
"logid", "")
SQLCA.Logpass = ProfileString("myapp.ini", &
"database", "LogPassWord", "")
SQLCA.Servername = ProfileString("myapp.ini", &
"database", "servername", "")
SQLCA.DBParm = ProfileString("myapp.ini", "database", &
"dbparm", "")

CONNECT;

IF SQLCA.Sqlcode <> 0 THEN


MessageBox("Cannot Connect to Database", &
SQLCA.SQLErrText)
RETURN
END IF

/* Open MDI frame window */


Open(w_genapp_frame)

See also
Close

2.3.87.2 Syntax 2: For windows


Description
Occurs when a window is opened by one of the Open functions. The event occurs after the
window has been opened but before it is displayed.
Event ID

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

This code does not cause a crash:


// w_1 ue_postopen event script
close(this)

// w_1 Open event script


open(w_2)
this.Post Event ue_postopen()

Changing the WindowState property


Do not change the WindowState property in the Open event of a window opened as a
sheet. Doing so might result in duplicate controls on the title bar. You can change the
property in other scripts once the window is open.

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

This.Position = This.Position + ii_pagesize


ll_currow = dw_1.GetRow()
ll_nextrow = ll_currow + 10
dw_1.ScrollToRow(ll_nextrow)
dw_1.SetRow(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.

• For dragging the thumb itself, use the Moved event.

Examples
This code in the PageRight event causes the thumb to move right when the user clicks on
the right arrow of the horizontal 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.

• For dragging the thumb itself, use the Moved event.

Examples
Example 1
This code in the PageUp event causes the thumb to move up when the user clicks on the up
arrow of the vertical 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

2.3.97 PrintFooter (obsolete)


Description
Occurs when the footer of a page of the document in the RichTextEdit control is about to be
printed.

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

2.3.98 PrintHeader (obsolete)


Description
Occurs when the header of a page of the document in the RichTextEdit control is about to be
printed.

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

Occurs periodically during synchronization after updates to a synchronization progress bar.


Event ID

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

None (do not use a RETURN statement)


Usage
Property change notifications are not supported by all OLE servers. The PropertyRequestEdit
and PropertyChanged events occur only 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 PropertyChanged event occurs after the property's value has changed. You can obtain the
new value through the automation interface. The change can no longer be canceled. If you
want to cancel a change, write a script for the PropertyRequestEdit event.
See also
DataChange
PropertyRequestEdit
Rename
ViewChange

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:

• FALSE -- (Default) the change is allowed.

• TRUE -- the change is canceled.

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

2.3.104.1 Syntax 1: For controls and windows, except RichTextEdit


Description
For a window, occurs when the right mouse button is pressed in an unoccupied area of the
window (any area with no visible, enabled object). The window event will occur if the cursor
is over an invisible or disabled control.
For a control, occurs when the right mouse button is pressed on the control.
Event ID

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:

• 1 -- Left mouse button

• 2 -- Right mouse button

• 4 -- Shift key

• 8 -- Ctrl key

• 16 -- Middle mouse button

In the RButtonDown event, the right mouse button is always pressed, so


2 is always summed in the value of flags.
For an explanation of flags, see Syntax 2 of MouseMove.
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
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

2.3.104.2 Syntax 2: For RichTextEdit controls


Description
Occurs when the user presses the right mouse button on the RichTextEdit control and the
control's PopMenu property is set to false.

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

Return code choices (specify in a RETURN statement):


0 -- Continue processing
See also
RemoteExec
RemoteSend

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

Return code: Ignored


Usage
If you want to retrieve the ObjectData blob value of an OLE control during the processing of
this event, you must post a user event back to the control or you will generate a runtime error.
See also
DataChange
PropertyRequestEdit
PropertyChanged
ViewChange

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:

• 0 -- (SIZE_RESTORED) The window or DataWindow has been


resized, but it was not minimized or maximized. The user might have
dragged the borders or a script might have called the Resize function.

• 1 -- (SIZE_MINIMIZED) The window or DataWindow has been


minimized.

• 2 -- (SIZE_MAXIMIZED) The window or DataWindow has been


maximized.

• 3 -- (SIZE_MAXSHOW) This window is a pop-up window and some


other window in the application has been restored to its former size
(does not apply to DataWindow controls).

• 4 -- (SIZE_MAXHIDE) This window is a pop-up window and some


other window in the application has been maximized (does not apply to
DataWindow controls).

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

2.3.115.1 Syntax 1: For ListView and Tab controls


Description
Occurs when the user clicks the right mouse button on the ListView control or the tab portion
of the Tab control.
Event ID

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

// Display menu at pointerposition


m_lv_popmenu.m_entry.PopMenu(Parent.PointerX(), &
Parent.PointerY())

See also
Clicked
RightDoubleClicked

2.3.115.2 Syntax 2: For TreeView controls


Description
Occurs when the user clicks the right mouse button on the TreeView control.
Event ID

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

// Create an instance of the menu variable


m_tv_popmenu = CREATE m_main

// Display menu at pointer position


m_tv_popmenu.m_entry.PopMenu(Parent.PointerX(), &
Parent.PointerY())

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

2.3.116.1 Syntax 1: For ListView and Tab controls


Description
Occurs when the user double-clicks the right mouse button on the ListView control or the tab
portion of the Tab control.
Event ID

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

// Delete the item


li_rtn = This.DeleteItem(index)

IF li_rtn = 1 THEN
This.Arrange( )
ELSE
MessageBox("Error", Deletion failed!")
END IF

See also
DoubleClicked
RightClicked

Page 314
Statements, Events, and Functions

2.3.116.2 Syntax 2: For TreeView controls


Description
Occurs when the user double-clicks the right mouse button on the TreeView control.
Event ID

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)

IF ll_row > 0 THEN


// Make the found row current
dw_1.SetRow(ll_row)

// Put today's date in the last_updated column


dw_1.Object.last_updated[ll_row] = Today( )

// Update and refresh the DataWindow


dw_1.Update( )
dw_1.Retrieve( )
ELSE
MessageBox("Find", "No row found")
END IF

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

2.3.119.1 Syntax 1: For Ribbon controls


Description
This is a user event which occurs when the user highlights an item within the RibbonBar
control.
Make sure the parameter (quantities and types) of the user event is correctly defined
according to the requirement of the ribbon control.
Applies to
Ribbon controls (including RibbonTabButtonItem, RibbonLargeButtonItem,
RibbonSmallButtonItem, RibbonCheckBoxItem, RibbonComboBoxItem, and
RibbonMenuItem)
Arguments for RibbonTabButtonItem, RibbonLargeButtonItem,
RibbonSmallButtonItem, RibbonCheckBoxItem, RibbonComboBoxItem

Page 317
Statements, Events, and Functions

Table 2.303:
Argument Description
ItemHandle Long. The handle of the item.

Arguments for RibbonMenuItem (of Normal(0) type)

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.

Arguments for RibbonMenuItem (of Recent(2) type)

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"

//Ue_TabButtonSelected user event must have a long parameter for receiving


//the handle of TabButton where the mouse is hovering, as below
event type long ue_tabbuttonselected(long itemhandle);
RibbonTabButtonItem lr_TabButton
rbb_1.GetTabButton(ItemHandle,lr_TabButton)
//...
Return 1
end event

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:

event type long ue_menuselected(long itemhandle, long index, long subindex);


Integer li_Return
RibbonMenu lr_Menu
RibbonMenuItem lr_MenuItem

li_Return = rbb_1.GetMenuByButtonHandle(ItemHandle, lr_Menu)


If li_Return = 1 Then
If SubIndex = 0 Then
li_Return = lr_Menu.GetItem(Index, lr_MenuItem)
//...
Else
li_Return = lr_Menu.GetItem(Index, SubIndex, lr_MenuItem)
//...
End If
Else
Return 0
End If

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:

event type long ue_mastermenuselected(long itemhandle, long index, long subindex);


Integer li_Return
RibbonApplicationMenu lr_Menu
RibbonMenuItem lr_MenuItem

li_Return = rbb_1.GetMenuByButtonHandle(ItemHandle, lr_Menu)


If li_Return = 1 Then
If SubIndex = 0 Then
li_Return = lr_Menu.GetMasterItem(Index, lr_MenuItem)
//...
Else
li_Return = lr_Menu.GetMasterItem(Index, SubIndex, lr_MenuItem)
//...
End If
Else
Return 0
End If

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

2.3.119.2 Syntax 2: for all other controls


Description
Occurs when the user highlights an item on the menu using the arrow keys or the mouse,
without choosing it to be executed.
Event ID

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

2.3.120.1 Syntax 1: For Listboxes


Description
Occurs when an item is selected in the control.
Event ID

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)

// Clear out categories, series and data from graph


gr_1.Reset(All!)

// Loop through all selected values and


// create as many series as the user specified
FOR i = 1 to lb_value.TotalItems()
IF lb_value.State(i) = 1 THEN
ls_colname = lb_value.Text(i)

// Call window function to set up the graph


wf_set_a_series(ls_colname, ls_colname, &
lb_category.text(1))
END IF
NEXT
gr_1.SetRedraw(TRUE)

See also
Clicked

2.3.120.2 Syntax 2: For Tab controls


Description
Occurs when a tab is selected.
Event ID

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

2.3.120.3 Syntax 3: For TreeView controls


Description
Occurs when the item is selected in a TreeView control.
Event ID

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

TreeViewItem l_tvinew, l_tviold

// get the treeview item that was the old selection


This.GetItem(oldhandle, l_tviold)

// get the treeview item that is currently selected


This.GetItem(newhandle, l_tvinew)

// Display the labels for the two items in sle_get


sle_get.Text = "Selection changed from " &
+ String(l_tviold.Label) + " to " &
+ String(l_tvinew.Label)

See also
Clicked
SelectionChanging

2.3.120.4 Syntax 4: For Ribbon controls


Description
This is a user event which occurs when the item is selected in the ribbon combo box control.
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.314:
Argument Description
ItemHandle Long. The handle of the item.
index Long. The index of the item selected.

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

2.3.121.1 Syntax 1: For Tab controls


Description
Occurs when another tab is about to be selected.
Event ID

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

2.3.121.2 Syntax 2: For TreeView controls


Description
Occurs when the selection is about to change in the TreeView control.
Event ID

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

// Get TreeViewItem that was the old selection


This.GetItem(oldhandle, l_tviold)

// Get TreeViewItem that is currently selected


This.GetItem(newhandle, l_tvinew)

//Display the labels for the two items in display


sle_status.Text = "Selection changed from " &
+ String(l_tviold.Label) + " to " &
+ String(l_tvinew.Label)

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:

• 0 -- The current window is the only one affected.

• 1 -- The window's parent is also being minimized or a pop-up window


is being hidden.

• 3 -- The window's parent is also being displayed or maximized or a


pop-up window is being shown.

Return Values
Long.
Return code choices (specify in a RETURN statement):
0 -- Continue processing
Usage

Page 327
Statements, Events, and Functions

The Show event occurs when the window is opened.


See also
Activate
Hide
Open

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

2.3.124.1 Syntax 1: For ListView controls


Description

Page 328