Comprehensive Delphi Delphi Cram Notes and Study Notes Guide
Component Basics and Properties
Edit Box (.Text)
What it does: Extracts or sets the text displayed in the Edit Box.
Extract Example:
sName := edtName.Text;Set Example:
edtName.Text := sName;oredtName.Text := ‘Angela’;
Combo Box (.Text)
What it does: Extracts or sets the text displayed in the Combo Box.
Extract Example:
sData := cmbData.Text;Set Example:
cmbData.Text := sName;orcmbData.Text := ‘Adhi’;
ComboBox (.ItemIndex)
What it does: Returns the index of the user’s selection from the ComboBox. The index starts at .
Extract Example:
iSel := cmbData.ItemIndex;Set Example:
cmbData.ItemIndex := 0;(This sets the selection to the first item).
Radio Group (.Items)
What it does: Extracts or adds option/option text to the Radio Group.
Extract Example:
sSel := rgpData.Items[rgpItems.ItemIndex];orsSel := rgpData.Items[0];Set Example:
rgpData.Items.Add(‘Coffee’);
Radio Group (.ItemIndex)
What it does: Returns the index of the user’s selection from the Radio Group. The index starts at .
Extract Example:
iSel := rgpData.ItemIndex;Set Example:
rgpData.ItemIndex := 0;(This sets the selection to the first item).
List Box (.Items)
What it does: Extracts or adds option/option text to the List Box.
Extract Example:
sSel := lstData.Items[lstData.ItemIndex];orsSel := lstData.Items[0];Set Example:
lstData.Items.Add(‘Hot Chocolate’);
List Box (.ItemIndex)
What it does: Returns the index of the user’s selection from the List Box. The index starts at .
Extract Example:
iSel := lstData.ItemIndex;Set Example:
lstData.ItemIndex := 0;(This sets the selection to the first item).
Checkbox (.Checked)
What it does: Returns a Boolean value where TRUE means the box is checked and FALSE means it is not checked.
Extract Example:
bMarried := chbMarried.Checked;Set Example:
chbMarried.Checked := TRUE;(This ticks the box).
Label (.Caption)
What it does: Extracts or sets the text displayed on the label.
Extract Example:
sText := lblHeading.Caption;Set Example:
lblHeading.Caption := ‘Hello’;orlblHeading.Caption := sText;
Panel (.Caption)
What it does: Extracts or sets the text displayed on the panel.
Extract Example:
sText := pnlWelcome.Caption;Set Example:
pnlWelcome.Caption := ‘Hello’;orpnlWelcome.Caption := sText;
Rich Edit Box (.Text)
What it does: Extracts, clears, and displays text.
Extract Example:
sLine := redOut.Text;Set Example:
redOut.Text := ‘Hello’ + #9 + sName + #13 + ‘How are you?’;Constants used:
#9represents a tabspace;#13represents a new line.
Rich Edit Box (.Lines.Add)
What it does: Adds a new line and displays provided text.
Set Example:
redOut.Lines.Add(‘Hello’);
Rich Edit Box (.SelText)
What it does: Adds data to the existing current line in the Rich Edit Box without moving to a new line.
Set Example:
redOut.SelText := ‘Hello’ + #9 + sName;
SpinEdit (.Value)
What it does: Sets or returns the selected or typed numerical value.
Extract Example:
iAge := sedAge.Value;Set Example:
sedAge.Value := 16;
DateTimePicker (.Date)
What it does: Returns or sets the selected date.
Extract Example:
dtDate := dtPurchase.Date;Set Example:
dtPurchase.Date := StrToDate(‘08/10/2018’);
DateTimePicker (.Time)
What it does: Returns or sets the selected time.
Extract Example:
dtTime := dtPurchase.Time;Set Example:
dtPurchase.Time := StrToTime(’16:49:20’);
ImageBox (.Picture)
What it does: Displays a picture based on a specified filename.
Action Example:
imgProd.Picture.LoadFromFile(‘RedBull.jpg’);
MemoBox (.Text / .Lines)
Details: Uses the same structure and methods (e.g.,
.Text,.Lines.Add) as the Rich Edit Box.
Pre-defined Math Class Methods
Round
Action: Rounds a real number to the nearest whole number.
Return Type: Integer.
Example:
rValue := 5 / 2; iValue := Round(rValue);(Results iniValue = 3).
Frac
Action: Returns the fractional (decimal) part of a number.
Return Type: Real.
Example:
rValue := 10 / 3; rNew := Frac(rValue);(Results inrNew = 0.3333).
Ceil
Action: Rounds a fractional value up to the next integer.
Return Type: Integer.
Example:
rValue := 10 / 3; rNew := Ceil(rValue);(Results inrNew = 4).
Floor
Action: Rounds a fractional value down to the nearest integer.
Return Type: Integer.
Example:
rValue := 5 / 3; rNew := Floor(rValue);(Results inrNew = 1).
FormatFloat
Action: Converts a Real value to a formatted String.
Return Type: String.
Example 1:
sOutput := FormatFloat(‘0.0’, 5.253);(Results insOutput = 5.3).Example 2:
sOutput := FormatFloat(‘R0.00’, 5.253);(Results insOutput = R5.25).
Trunc
Action: Removes the decimal part of a Real number (truncates).
Return Type: Integer/Real.
Example:
rValue := 3.55; rNew := trunc(rValue);(Results inrNew = 3).
Power
Action: Raises a base value to a specific exponent value.
Return Type: Real.
Example:
rPow := power(5, 3);(Results inrPow = 125).
Sqrt
Action: Calculates the square root of a provided value.
Return Type: Real.
Example:
rSR := sqrt(64);(Results inrSR = 8).
Max
Action: Returns the higher value between two provided numbers.
Return Type: Integer/Real.
Example:
iBig := max(50, 20);(Results iniBig = 50).
Min
Action: Returns the smaller value between two provided numbers.
Return Type: Integer/Real.
Example:
iSmall := min(50, 20);(Results iniSmall = 20).
Abs
Action: Returns the absolute value (positive distance from zero) of a number.
Return Type: Integer/Real.
Example:
rNum := 30 - 50; rNum := abs(rNum);(Results inrNum = 20).
Pi
Action: Returns the constant value of .
Return Type: Real.
Example:
rCircleArea := pi * power(rRadius, 2);
Val
Action: Attempts to convert a String to a Real number. If successful, returns an error code of . If unsuccessful, returns the index position of the error.
Return Type: Integer (for Error Code), Real (for converted value).
Example 1:
val(‘500’, rNum, iError);(Results inrNum = 500,iError = 0).Example 2:
val(‘5A5’, rNum, iError);(Results inrNum = undefined,iError = 2).
Succ
Action: Returns the successor (next value) of the provided integer or character.
Return Type: Integer/Char.
Example:
iNum := 50; iNum := succ(iNum);(Results iniNum = 51).
Pred
Action: Returns the predecessor (previous value) of the provided value.
Return Type: Integer/Char.
Example:
iNum := 49; iNum := pred(iNum);(Results iniNum = 48- corrected from transcript typo which listed 49/49 outcomes).
RandomRange
Action: Returns a random integer between a minimum and a maximum minus 1 ( to ).
Return Type: Integer.
Example:
iRan := RandomRange(50, 100);(Range: ).
Random
Action: Returns a random integer from up to the specified value minus 1.
Return Type: Integer.
Example:
iRan := Random(100);(Range: ).
Sign
Action: Returns an integer indicating the sign of the number ( for negative, for zero, for positive).
Example:
iSign := Sign(-205);(Results iniSign = -1).
CompareValue
Action: Compares two values and returns if the first is greater, if smaller, or if equal.
Example:
iCom := CompareValue(150, 100);(Results iniCom = 1).
Annexure B: Components, Events, and Methods Matrix
Key Components and Grades (10, 11, 12):
Grade 10: TForm, TButton, TBitButton, TLabel, TEdit, TImage, TShape, TPanel, TListBox, TRadioGroup, TComboBox, TMemo, TRadioButton, TCheckBox.
Grade 11: TSpinEdit, TTimer, TStringGrid, TDBGrid.
Grade 12: TPageControl, TADOTable, TADOQuery, TDataSource.
General Methods:
Show(),Hide(),SetFocus().Grade 11 Addition:
setLength.
Conversion and Formatting:
IntToStr(),StrToInt(),FloatToStr(),StrToFloat(),FloatToStrF()(Grade 11).Date/Time:
FormatDateTime(),TimeToStr(),DateToStr(),DateTimeToStr(),StrToDate(),StrToTime().
Mathematical Methods:
Random(),RandomRange(),Round(),Trunc(),Frac(),Ceil()(Grade 11),Floor()(Grade 11),Sqr(),Sqrt(),Pi(Grade 11),Power()(Grade 11).Inc(),Dec()(Grade 10).
String Handling:
Length(),Pos(),Copy(),Insert(),Delete(),Concat(),UpCase(),UpperCase(),LowerCase(),IgnoreCase()(Grade 11).Ord(),Chr(),Val(),Str.
File Handling:
AssignFile(),Append(),Reset(),Rewrite(),CloseFile(),FileExists(),Readln(),Writeln(),LoadFromFile(),SaveToFile().
UI and Messages:
InputBox(),ShowMessage(),MessageDlg()(Grade 11).
Event Handlers:
OnClick,OnCreate,OnActivate,OnShow,OnClose,OnTimer.
Database Code Constructs
General Reading Structure:
tblExample.First;
while not tblExample.EOF do
Begin
// Process Record
tblExample.Next;
End;
```
- **Calculating Sum and Average:**
pascal tblExample.First; rSum := 0; while not tblExample.EOF do Begin rSum := rSum + tblExample[‘Age’]; tblExample.Next; End; rAve := rSum / tblExample.RecordCount; ```
Finding Highest Value:
tblExample.First;
iHigh := tblExample[‘Age’];
while not tblExample.EOF do
begin
if tblExample[‘Age’] > iHigh then
begin
iHigh := tblExample[‘Age’];
end;
tblExample.Next;
end;
// Note: Swap the > to < in the IF statement to find the Lowest value.
```
- **Updating the Current Record:**
pascal tblExample.Edit; tblExample[‘Name’] := ‘Erica’; tblExample[‘Age’] := 17; tblExample.Post; tblExample.Refresh; ```
Adding a New Record:
tblExample.Append;
tblExample[‘ID’] := IntToStr(tblExample.RecordCount + 1);
tblExample[‘Name’] := ‘Ndumiso’;
tblExample[‘Age’] := 17;
tblExample.Post;
tblExample.Refresh;
```
- **Deleting current Record:**
- Use `tblExample.Delete;`.
- Important: In practical applications, always use a confirmation dialog box before finalizing a delete.
- **Locating a Specific Record:**
pascal sName := edtName.Text; bFound := FALSE; tblExample.First; while not tblExample.EOF do Begin If tblExample[‘Name’] = sName then Begin bFound := TRUE; End; tblExample.Next; End; ```
Block Adjustment (e.g., Update all ages):
tblExample.First;
while not tblExample.EOF do
Begin
tblExample.Edit;
tblExample[‘Age’] := tblExample[‘Age’] + 1;
tblExample.Post;
tblExample.Refresh;
tblExample.Next;
End;
```
- **Counting (e.g., records with mark < 30):**
pascal iCount := 0; tblExample.First; while not tblExample.EOF do Begin If tblExample[‘Mark’] < 30 then Begin Inc(iCount); End; tblExample.Next; End; ```
Working with Two Tables (Parent and Child):
tblParent.First;
while not tblParent.EOF do
Begin
// obtain a pk field
tblChild.First;
while not tblChild.EOF do
Begin
If tblParent[‘PK’] = tblChild[‘FK’] then
Begin
// Action logic
End;
TblChild.Next;
End;
tblParent.Next;
End;
```
- **Sorting Records:**
- Syntax: `Tblname.sort := ‘Field ASC’;` (for ascending) or `Tblname.sort := ‘Field DESC’;` (for descending).
# Data Validation Examples
- **Text Only (A-Z, a-z):**
pascal bValid := TRUE; for i := 1 to Length(sWord) do Begin If not(sWord[i] in [‘A’..’Z’, ‘a’..’z’]) then Begin bValid := FALSE; End; End; ```
Text with Spaces and Length Check:
bValid := TRUE;
for i := 1 to Length(sWord) do
Begin
If not(sWord[i] in [‘A’..’Z’, ‘a’..’z’, ‘ ’]) then
bValid := FALSE;
End;
If (Length(sWord) = 13) AND (bValid) then // Condition met
```
- **Digits Only (0-9):**
pascal bValid := TRUE; for i := 1 to Length(sWord) do Begin If not(sWord[i] in [‘0’..’9’]) then bValid := FALSE; End; ```
Text File Handling
Checking File Existence:
Exist check:
If FileExists(‘data.txt’) then...Non-existence check:
If not FileExists(‘data.txt’) then...
Reading from a Text File:
AssignFile(tFile, ‘data.txt’);
Reset(tFile);
While not eof(tFile) do
Begin
ReadLn(tFile, sLine);
End;
CloseFile(tFile);
```
- **Creating and Writing to a New Text File:**
pascal AssignFile(tFile, ‘new.txt’); Rewrite(tFile); WriteLn(tFile, sLine); CloseFile(tFile); ```
Appending to an Existing Text File:
AssignFile(tFile, ‘myfile.txt’);
Append(tFile);
WriteLn(tFile, sLine);
CloseFile(tFile);
```
# One-Dimensional Arrays
- **Declaration:** `arrNum : Array[1..5] of Integer;`
- **Declaration with Initial Values:** `arrNum : Array[1..5] of Integer = (10, 50, 40, 100, 80);`
- **Populating with Random Values (Range ):**
pascal For i := 1 to 5 do arrNum[i] := RandomRange(1, 101); ```
Populating with User Input:
For i := 1 to 5 do
arrNum[i] := StrToInt(InputBox(‘Cram’, ‘Enter number’, ‘’));
```
- **Displaying Values:**
- **Vertically (RichEdit):** `redOut.Lines.Add(IntToStr(arrNum[i]));`
- **Horizontally (EditBox):** `edtOut.SelText := IntToStr(arrNum[i]) + #9;` (using tabspace).
- **Sum and Average:**
pascal rSum := 0; For i := 1 to 5 do rSum := rSum + arrNum[i]; rAve := rSum / Length(arrNum); ```
Finding Highest in Parallel Arrays:
iHigh := arrNum[1];
sName := arrNames[1];
for i := 2 to 5 do
begin
if arrNum[i] > iHigh then
begin
iHigh := arrNum[i];
sName := arrNames[i];
end;
end;
```
- **Bubble Sort (Parallel Array Example):**
pascal iEndCounter := Length(arrTitle) - 1; repeat bSwapped := false; for k := 1 to iEndCounter do begin if arrTitle[k] > arrTitle[k + 1] then begin sKeep := arrTitle[k]; arrTitle[k] := arrTitle[k + 1]; arrTitle[k + 1] := sKeep; bSwapped := true; end; end; until (bSwapped = false); // For descending order, change the > to <. ```
Searching and Array Manipulation:
Search: If
iPosremains after a loop through the array, the item was not found.Delete: Move items from
iPosupward toiMax - 1and decrement the size counter (dec(iMax)).pascal for i := iPos to iMax - 1 do arrNum[i] := arrNum[i + 1]; dec(iMax);
Two-Dimensional Arrays
Declaration:
arrNum : Array[1..5, 1..4] of Integer;(5 Rows, 4 Columns). Always reference Row () first, then Column ().Displaying in a StringGrid:
Note: In a StringGrid, Column comes before Row:
StringGrid1.Cells[c, r].Column/Row usually contains headings.
Transposing:
Converting Rows to Columns:
arrNew[r][c] := arrNum[c][r];. Ensure the new array has swapped row/column dimensions.
Diagonal Calculations (Square Arrays Only):
Left Diagonal (): Loop
iSum := iSum + arrNum[r][r];from to .Right Diagonal (/): Start
cat the max column and decrement while looping rows:iSum := iSum + arrNum[r][c]; dec(c);.
Swapping Logic:
Swap Rows: Use a loop for columns and a temp variable:
iTemp := arrNum[r1][c]; arrNum[r1][c] := arrNum[r2][c]; arrNum[r2][c] := iTemp;.Swap Columns: Use a loop for rows:
iTemp := arrNum[r][c1]; arrNum[r][c1] := arrNum[r][c2]; arrNum[r][c2] := iTemp;.
Object-Oriented Programming (OOP)
Constructor:
Declaration:
Constructor CREATE(sName : String; sID : String);Implementation: Used to initialize private attributes (e.g.,
fName := sName;).
Accessor (Getter):
A function returning an attribute value. Example:
Function TClass.getAge : Integer; Begin Result := fAge; End;.
Mutator (Setter):
A procedure to change an attribute. Example:
Procedure TClass.setAge(iAge : Integer); Begin fAge := iAge; End;.
toString:
A function returning a user-friendly string of attributes:
Result := ‘Key: ’ + #9 + fName;.
Instantiation:
Syntax:
objLearner := TLearner.Create(sName, sID);.
String Handling Methods and Properties
Indexing:
sSent[i]refers to a single character (type Char).Set Inclusion:
If sSent[i] in [‘a’, ‘e’, ‘i’, ‘o’, ‘u’] then...Key Procedures:
Insert(sSub, sLine, iPos): Adds a string into another at a position.Delete(sLine, iStart, iNumChars): Removes characters from a string.
Key Functions:
Length(sString): Returns integer length.Pos(sSub, sMain): Returns integer starting position of a substring.Copy(sString, iStart, iLen): Returns a substring.Uppercase(sString)/Upcase(Char): Converts to capitals.
Time, Date, and Pop-up Dialogs
Functions:
Now(): Current date and time.Date(): Current system date.Time(): Current system time.IsLeapYear(Year): Returns Boolean TRUE if leap year.YearOf(dDate),MonthOf(dDate),DayOf(dDate): Extract components as integers.
MessageDlg:
Syntax:
If MessageDLG(‘Exit?’, mtWarning, [mbOK, mbCancel], 0) = mrOK then...Types:
mtWarning,mtConfirmation,mtInformation,mtError,mtCustom.Buttons:
mbYes,mbNo,mbOK,mbCancel,mbAbort,mbRetry,mbIgnore,mbAll.Return values:
mrYes,mrNo,mrOK,mrCancel, etc.
Mathematical Functions Summary
Sqr(num): Returns the square (). Example:
sqr(-5) = 25.Sqrt(num): Returns the square root (). Example:
sqrt(9) = 3.Abs(num): Returns absolute positive value. Example:
abs(-10) = 10.Formula for Random Range:
Random(big - small + 1) + start.Ceil/Floor Examples:
Ceil(8.2) = 9Ceil(-3.1) = -3Floor(8.7) = 8Floor(-3.1) = -4
Programming Error Types
Syntax error: Errors in the use of the programming language (e.g., missing semicolon).
Logical error (Semantic error): Incorrect results produced due to a flawed algorithm.
Run-time error: Occurs while the program is running, potentially causing crashes (e.g., division by zero, square root of negative numbers).