Вы находитесь на странице: 1из 10

Main Menu Bar

- Special area displaying across top of form


- Includes set of choices menu titles
- Each menu title has drop-down menu collection of menu items
- Content of menu bar and drop-down menus depend on functionality of application and user
interaction

Can include underscore character (accelerator key) access menu item using Alt key
Elipsis (three dots) next to item (Save As . . .) dialog box appears on screen for additional information
Right-pointing arrow next to item (Reopen) indicate cascading submenu connected to it
Dimmed item means option currently not available
Separate groups options with horizontal lines (separator lines)
Name := mnu_Name
MenuItem = Delphi component representing single choice on menu can be drop-down menu or
particular menu option invoking program command
First entrance is title for drop-down menu. Delphi automatic assign intelligible name to menu items
Name property, based on Caption given.
Hyphen (-) insert separator line

procedure TfrmChameleon.Exit1Click(Sender: TObject);
begin
close;
end;

Create shortcut select Shortcut property and select Ctrl+X from list which will add shortcut

Shortcuts versus accelerator keys
Both allow user to invoke action using keyboard instead of mouse
Relevant menu item must be visible for accelerator keys (<Alt>key) to work
Shortcut keys are positive feature of user interface (<Ctrl>+key)

Delete MenuItem by selecting item inside Menu editor and pressing <Del>
Insert MenuItem, select item in front of which to insert and press <Ins>

Can expand menu in two directions:
- Extending main menu bar
- Adding items for drop-down meu

TMainMenu
Property Items Defines items (of type TMenuItem) displayed in menu
Prefix mnu . . .
Use Maintain menu bar with associated drop-down menus

TMenuItem
Properties Actions Contain name of Action associated with menu item
Caption Contains string displayed as menu item
Events OnClick Triggered when user click menu item or uses relevant accelerator or shortcut
Use Determines appearance and behaviour of item in menu








ColorDialog Component
ColorDialog allow user to select any colour available in Windows environment.

// set colour highlighted on colour palette to forms colour
cdlChamelean.Color := frmChameleon.Color;
// Call to Execute method of cdlChameloen activate ColorDialog component for user to select
// colour. Program waits for user input. If OK execution return True and execute If statement //
to change the form colour
if cdlChameleon.Execute then
frmChameleon.Color := cdlChameleon.Color;

TColorDialog
Properties Color: Contains current selected colour
Methods Execute: Call to this method opens Color dialog. Execute returns True if user
Clicks OK or Flase if user clicks Cancel or closes dialog
Prefix cdl . . .
Use Display Windows common dialogue to selecting Colour. When click OK, return colour
in Colour property

Cascading Submenus
Use of deeply nested cascading menus not recommended:
- Multi-level cascading menus difficult for user to manipulate, because every time item chosen from
bottom-level menu, entire cascade disappears
- User must navigate explicitly all the way down through cascade to restore context in menu
- Easy to issue wrong, unintended command when in cascading menu
procedure TfrmChameleon.Bold1Click(Sender: TObject);
begin
if Bold1.Checked then //if the bold item is already checked
begin
lblChameleon.Font.Style := lblChameleon.Font.Style - [fsbold];
bold1.Checked := false; //remove Bold check mark
end
else
begin
lblChameleon.Font.Style := lblChameleon.Font.Style + [fsbold];
bold1.Checked := true; //remove Bold check mark
end;
end;

MenuItems Checked property determines whether check mark appears next to item indicate it is on or off

bold1.Checked := False; //MenuItem unchecked
bold1.Checked := True; //MenuItem checked
Two statements can be changed to be combined into single statement outside If statement:
Bold1.Checked := not (Bold1.Checked);
Affect of single statement is to set Checked property to opposite of what was before
Simplify event handler as follow:
procedure TfrmChameleon.Bold1Click(Sender: TObject);
begin
if Bold1.Checked then //if the bold item is already checked
lblChameleon.Font.Style := lblChameleon.Font.Style - [fsbold]
else
lblChameleon.Font.Style := lblChameleon.Font.Style + [fsbold];
Bold1.Checked := not (Bold1.Checked); //Toggle Bold check mark
end;

procedure TfrmChameleon.Italic1Click(Sender: TObject);
begin
if Italic1.Checked then //if the bold item is already checked
lblChameleon.Font.Style := lblChameleon.Font.Style - [fsItalic]
else
lblChameleon.Font.Style := lblChameleon.Font.Style + [fsItalic];
Italic1.Checked := not(Italic1.Checked); //remove Bold check mark
end;

procedure TfrmChameleon.Underline1Click(Sender: TObject);
begin
if Underline1.Checked then //if the bold item is already checked
lblChameleon.Font.Style := lblChameleon.Font.Style - [fsUnderline]
else
lblChameleon.Font.Style := lblChameleon.Font.Style + [fsUnderline];
Underline1.Checked := not(Underline1.Checked); //remove Bold check mark
end;

Sets
- Like array, set is collection of data elements of same type.
- While array elements are ordered and access individual elements through index
- Sets elements are not ordered and cannot access individual elements
- Can only check if given element appears in set
- Same element cannot appear in set more than once, array can contain duplicates
- Delphi write set as list of values (called elements) separated by commas and enclosed in square
brackets example [1, 2, 3], which is set containing three integer elements

IN three event handles that change font, used Font.Style property which is set contains elements of
type TFontStyle
Delphi TFontStyle type consists of values fsBold, fsItalic, fsUnderline and fsStrikeOut
Font.Style property takes values [fsBold], [fsItalic], [fsBold, fsItalic] and []
If Font.Style property of Label component equal to [fsBold], means Caption displayed in bold talics
Value [] {empty set} means Caption appears in regular font style

lblChameleon.Font.Style := lblChameleon.Font.Style - [fsbold]
// remove the element fsBold from the set lblChameleon.Font.Style,
// thereby removing bold face of lblChameleon Caption

lblChameleon.Font.Style := lblChameleon.Font.Style + [fsbold]
// adds fsBold to set changing Caption to bold

Can define own set variables
var
Digits: set of 0..9;
Detters1, Letters2, Letters3: set of a .. z;
With declarations can include assignment statements such as
Digits := [1, 3, 5, 7, 9];
Letters1 := [a, b, c];
Letters2 := [x, y];
Values on left- and right-hand sides of assignment operator must be of compatible types
Using in operator can test element appears in set with statement:
If sedInput.value in Digits then . . .
Checks SpinEdit values is one of 1, 3, 5, 7, 9
Can combine two sets with + operator:
Letters3 := Letters1 + Letters2; // Gives set with 5 elements
Letters1 := Letters1 + [d]; //Add letter d to Letters1
To remove element from set use (minus) operator:
Letters2 := Letters2 [x]; //Remove x from Letters2
Note both operands of + and operators are sets, and specifically sets of same element type

Adding pop-up menu
From Standard tab add PopupMenu component
Double click and add menu items
In Object inspector of Form drop-down list of available pop-up menus and associate nely added
popupMenu item
Name := pumName;
In Object Inspectorof popupMenu can assign already created events in the OnClick event handler

TPopupMenu
Property Items Defines items (of type TMenuItem) that are displayed in the menu
Prefix pum . . .
Use Defines pop-up menu displayed when user right click on component. Pop-up
menu associated with component specified in components PopupMenu property


Action List Component
From Standard Component Tab Action List component
Name := aclName;
Double click on to open Action list editor

TActionList
Properties Actions Contains indexed list of Actions in ActionList objects
Prefix acl . . .
Use Coordinates Actions. Place ActionList component on from and use Action list editor to
Maintain list of Actions contained in it. Can add Action to list, delete Action from list
and rearrange Actions

TAction
Properties Caption Text that will be linked to client Caption component
Enabled Determines whether client component is enabled or disabled
Shortcut If client component is menu item, key combination specify appear on
right of menu item
Event OnExecute Triggered by client components default event
Prefix act . . .
Use Centralises code and property values so multiple components can be linked to these
Properties and code through their Action properties



















DataBases:
InterBaseLibrary
Tables:
LibraryMember
(Interbase or
MySQL server
SQLConnection
Database
Connect to database using dbx Drivers.ini and
dbx connections.ini
Poperties:
Name = sco . . .
Driver = Interbase
ConnectionName = IBConnection
Driver = Database = enter path and
filename of database
Active = True
SQLDaraSet
General purpose Dataset, can retrieve entire
talbe, query or stored procedure results.
Use SQL query statements to get desired
records from database into application
Poperties:
Name = sds . . .
SQLConnection = sco . . .
CommandType = ctTable
CommandText = LibraryMember
Active = True
DataSetProvider
Connected to SQLDataSet and extract data
from dataset. Packaging data between
datasets communicates with: SQLDataSet and
ClientDataSet
Poperties:
Name = dsp . . .
DataSet = sds . . .
ClientDataSet
Stores data in memory, has ApplyUpdates
method used to update database (at other end
of chain of components) when changes are
mdae by user
Poperties:
Name = cds . . .
ProviderName = dsp . . .
DataControls
Gateway between
ClientDataSet and any data
aware components (in Data
Controls catagory of Tool
pallette eg DBGrid,
DBNavigator)
Poperties:
Name = dat . . .
DataSource
Link to data-aware, visual component on user
interface
Poperties:
Name = dat . . .
DataSet = cds . . .
Active = True 9Expand Dataset
property to find this


Changes made in DBGrid are applied to memory and not to database. Only applied to local in-memory
ClientDataSet

When closing application need to update database calling ApplyUpdates method of TClientDataSet:
procedure TfrmMember.FormClose(Sender: TObject; var Action: TCloseAction);
begin
if cdsMember.ChangeCount > 0 then
cdsMember.ApplyUpdates(0); //MaxErrors parameter: 0
end;

ChangeCount indicates number changes made to in-memory ClientDataSet that will be applied to
Database. If value zero, no changes made since last update.. Check value to avoid unnecessary call to
ApplyUdates.

MaxErrors parameter (0) indicates maximum errors provider allow before prematurely stopping
update. -1 used to indicate no limit to number errors

Undo Data Updates:
Changes kept in memory until applying update. Possible to undo changes before made permanent.
Provide Undo button allow reverse changes made
procedure TfrmMember.bmbUndoLasteChangeClick(Sender: TObject);
begin
cdsMember.UndoLastChange(True);
end;
UndoLastChange undoes last edit, insert or delete operation to record in ClientDataSet.
Argument specifies reposition of cursor on restored record. True = cursor positioned on restored
record. False = cursor remains on current active record

Opening and closing data sets correctly:
Connected property of SQLConnection to True
Active properties of SQLDataSet and DataSource properties to True.
Result live data during design time
Ensure SQLConnected not connected by setting Connected to False.
Nothing Active at design time prevents run-time errors, but has to open ClientDataSets
explicitly when form created. Use OnShow event handler of main form.

Set Connected of scoMyVPLibrary and Active of sdsMember and cdsMember to False.
Event Handler to connect during FromShow:
procedure TfrmMember.FormShow(Sender: TObject);
begin
scoMyVPLibrary.Connected := True;
cdsMember.Open;
end;
procedure TfrmMember.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
if cdsMember.ChangeCount > 0 then
cdsMember.ApplyUpdates(0); //MaxErrors parameter: 0
cdsMember.Close;
end;

Data Controls:
Display data from database source, like a table, outside the application. Can optionally save changes to
database source. Each control needs to be associated with DataSource component for the control to
receive and manipulate data.
DBEdit
DBGrid
DBNavigator
DBComboBox

TClientDataSet (Data Access Tab)
Properties ProviderName Specifies external provider object (DataSetProvider) link ClientDataSet
to another source data set (example SQLDataSet). Provider specified
by ProviderName can reside in same application as ClientDataSet or in
application server running on another system
Active Determines client data set makes data available.
False = client data closed and cant manipulate or read data
True = data can be read or edited using ClientDataSet.
Setting true fills ClientDataSet with data
Methods ApplyUpdate Writes aupdated records to database
UndoLastChange Undo last edit to record in client data set
Prefix cds
Use In-memory data set. Buffer of records from data table Communicates with data table
through DataSetProvider
TDBEdit (Data Controls tab)
Properties DataSource Link to data set where components finds data
DataField Identifies field whose value represented by DBEdit
Text Represent contents of field
Prefix dbe
Use DBEdit enables edit database field

TDataSetProvider (Data Access tab)
Properties DataSet Links DataSetProvider to data set represented
Prefix dsp
Use Provide data from data set to client data set to sesolve updates from client data set
back to data set or underlying database server. When provider supplies data to client
data set, client data set reconstructs data in data packet to create, in-memory copy for
user access. When user access complete, client data set repackages any changed data
and sends updates back to provider. Provider applies updates to database data set

TDataSource component (Data Access tab)
Property DataSet Specifies data set which DataSource component serves as connector
to data-aware components
Prefix dat
Use Use DataSource component to provide connection between data set and data controls
on form that enable display, navigation and editing of data underlying data set.

TDBComboBox (Data Controls tab)
Properties DataField Specifies which field represented by DBComboBox. Display current
value of field and allow user set value of field on current record
DataSource Links to data set.
Items Supply values in list user can choose
Prefix dbc
Use Allow user change value of filed in current record of data set.

TDBGrid (Data Controls tab)
Property DataSource Link to data set where grid finds data
Prefix dbg
Use Display and manipulates records from data set in tabular grid

TDBNavigator (Data Control Tab)
Properties DataSource Identifies data set navigator manipulates
VisibleButtons Select buttons to appear on navigator
Prefix nav
Use Move through data in data set and to perform operations on data

TSQLConnection Component (dbExpress tab)
Property Connected True to establish connection to database server.
ConnectionName Named connection configuration (IBConnection)
DriverName Named connections (InterBase)
LibraryName dbxint.dll associated with driver specified by DriverName
VendorLib gds32.dll library supplied by database vendor
LoginPrompt Set to True to provide login support when establish connection
Prefix sco
Use Represent dbExpress database connection




TSQLDataSet (dbExpress tab)
Property SQLConnection Use to specify SQL connection object that connects database to
database server
CommandType Indicates type command that is contained in CommandText
CommandText Command type:
ctQuery = SQL statement dataset executes
ctStoredProc = Name of stored procedure
ctTable = Name of table on database server
SortFieldNames Specify fields used to order records in data set. Only used when
ctTable and primary key consist of more than one field
Prefix sds
Use General-purpose unidirectional data set for accessing database information useing
dbExpress


Showing forms: model and modeless
Styles which form can be shown:
Modeless: frmBook.Show;
Modal: formbook.ShowModal;
When form displayed modally, it is the only form that can accept input from user. Cannot interact with
other form that may be visible. Modal form must be closed before interaction can continue with any
other form.
When form displayed modeless (show method) all operations and all other loaded forms operations
are available. Can switch between any forms on display and activities in different part of application
can continue in parallel
Preferable to use modeless forms, allows user to switch between forms without closing one form and
open other (more economical).


SQLs SELECT statement
procedure TfrmAcquisition.FormShow(Sender: TObject);
begin
dmoLibrary.cdsBook.Close;
dmoLibrary.sdsBook.CommandType := ctQuery;
dmoLibrary.sdsBook.CommandText :=
'SELECT * from librarybook ORDER BY BOOKTITLE';
dmoLibrary.scoMyVPLibrary.Connected := True;
dmoLibrary.cdsBook.Open;
dmoLibrary.cdsAcquisition.Open;
end;

Add Uses DB after interface

SQLs command for retrieving records from a table or tables is SELECT.
SELECT command structure:
SELECT column1, column2, . . .
FROM table1, table2, . . .
WHERE selection_criteria

SELECT clause specify columns to see.
FROM clause specifies tables to get data from.
WHERE clause (optional) contain criteria identify which rows to retrieve
Asterisk (*) used to retrieve columns in table in order defined.
Implications of different settings of CommandType property:
- CommandType: ctTable
Indicating SQLDataSet to retrieve all records in database table
SQL generated automatically during run time by SQLDataSet SETECT * From LibraryMember
(without WHERE clause)
- CommandType: ctQuery
Want to retrieve only subset of records in table selected columns and specify SQL query in
CommandText property. If want to see data of all members with surname Jones use SQL
statement:
SELECT * FROM LibraryMember
Where LibraryMember.Surname = Jones
If only want to see initials amd email addresses of all Jones members, use SQL statement
SELECT LibraryMember.MemberInitials.LibraryMember.MemberEmail
FROM LibraryMember
WHERE LibraryMember.Surname = Jones
- CommandType:ctStoredProc
Want to retrieve only subset records from table or tables by executing SQL statement stored
in procedure. CommandText property to be set to name of stored procedure.

SQL statement retrieving only Fantasy category:
SELECT * from librarybook
Where BookCategory = Fantasy
ORDER BY BookTitle


Working with the ClienDataSet
RecordCount determine number of records in data set
//Adding record to acquisition table
Acq := dmoLibrary.cdsAcquisition.RecordCount + 1; //1st Acq Num
dmoLibrary.cdsAcquisition.Insert; //Insert new empty record
dmoLibrary.cdsAcquisition.FieldByName('ACQUISITIONNUMBER')
.AsString := AcqNumber;
dmoLibrary.cdsAcquisition.FieldByName('ACQUISITIONISBN')
.AsString := moLibrary.cdsBook.FieldByName('BOOKISBN')
.AsString;
dmoLibrary.cdsAcquisition.Post; //Saving new Record
Put values in AcquisitionNumber and AcquisitionISBN fields of current record.
AsFloat Read value of active record Double field or assign Double value to contents
of field
AsInteger Read value of active record Integer field or assign Integer value to contents
of field
AsBoolean Read value of active record Boolean field or assign Boolean value to contents
of field
AsDateTime Read value of active record DateTime field or assign DateTime value to
contents of field


Searching for specific record using FindKey method:
FindKey search data set for record whose find key field(s) match list value received as argument
dmoLibrary.cdsLoan.FindKey([Acquisition])
If more than one key value to search, separate with commas:
cdsReservation.Findkey([ReserNameValue, RoomNumberValue, DateValue])

ClientDataSet FindNearest method
dmoLibrary.cdsLoan.FindNearest([edtAcqNumber.Text]);
Move cursor to specific record in data set, or to first record in data set that is greater than acquisition
number as it is with each character the user adds.


DateTimePicker
Want user to enter dates or time
Visual component designed specially for entering dates or time
Under Win32 Component Tab
Property DateTime Get or set date(and time if relevant) marked on the calendar Value of
DateTIme must lie within range specified by MaxDate and MinDate
DateMode dmConBoc date mode represent ComboBox, except that drop-down
list replaced by a calendar illustrating from which users can select a
date
Prefix dtp
Use Visual component specifically for entering dates or times

Date Routines
Uses DateUtils
Var DueDate: TDateTime;
DayOfTheWeek Function return day of week of specific date as integer 1 to 7 (1 = Monday)
YearOf Function return year represented by specific TDateTime value. YeaOf return
Value 1 to 9999

TClientDataSet
Method Close Close sets Active property of data set to False.
dmoLibrary.cdsLoan.Close;
Delete Remove active record from database
dmoLibrary.cdsLoan.Delete;
Edit Permits editing of active record
dmoLibrary.cdsLoan.Edit; //Put data set in Edit mode
FieldByName Retrieve field information for field given its name. If field not exist
EDatabase Error exception.FindNearestCalling the FineNearest
method moves cursor to specific record in data set or first record
matches or greater than value specified in data set key(s)
DueDate := dmoLibrary.cdsLoan.FieldByName('LOANDUEDATE').AsDateTime;
FindKey FindKey search for specific record
First First record in data set active record
IsEmpty Determine if data set has records. Return true if data set does not
contain any records
Open Sets Active propert for data to true
dmoLibrary.cdsLoan.Open;
Prior Moves to previous record in data set
Refresh Ensures application has latest data from database
dmoLibrary.cdsLoan.Refresh;

TDBLoopupComboBox
Property DataSource Specify DataSource compoenent identifies data set lookup
compoenent represent
DataField Field whose value represented by DBLookupComboBox
ListSource Links DBLookupComboBox to lookup table that holds field actually
displayed in drop-down list
ListField Identifies field or fields whose values are displayed in drop-down list
of DBLookupComboBox
KeyField Identifies field in ListSource data set that must match value of
DataField property
Event onCloseUp Occurs when combobox list is closed
Prefix dlc
Use Provides drop-down list of items for filling fields that require data from another data
Set

Вам также может понравиться