SELECT MAX("ID") FROM "Users";you can do same for any other field, let's say FirstName
SELECT MAX("FirstName") FROM "Users";MAX - is a SQL function which returns the last entry in the specified table.
SELECT MAX("ID") FROM "Users";you can do same for any other field, let's say FirstName
SELECT MAX("FirstName") FROM "Users";MAX - is a SQL function which returns the last entry in the specified table.
Reactions: |
// your procedure/function var stream : TStream; begin // the insert query myQuery.SQL.Text := 'INSERT INTO "Mytable"("MyStreamField") VALUES(:RichEdit)'; // get TRichEdit as stream with helper function stream := RichEditToStream(myRichEdit); // create a new parameter with field type as ftBlob and parameter // type as ptInput myQuery.Params.CreateParam(ftBlob, 'RichEdit', ptInput); // now load the parameter from stream // we can also use myQuery.myQuery.Params[0].LoadFromStream(); myQuery.ParamByName('RichEdit').LoadFromStream(stream, ftBlob); // we free the stream here FreeAndNil(stream); // execute the sql myQuery.ExecSQL; // clear the parameters myQuery.Params.Clear; end;
Reactions: |
// this function extracts formatted string from a // TRichEdit/TDBRichEdit or descendant and returns it as a TStream function RichEditToStream(thisRichEdit: TRichEdit): TStream; var ss : TStringStream; begin ss := TStringStream.Create(EmptyStr); thisRichEdit.Lines.SaveToStream(ss); Result := ss; // you might need to set position to zero Result.Position := 0; // REMEMBER to free the stream variable end; // this functions returns the formatted of a // TRichEdit/TDBRichEdit or descendant as plain string function RichEditToString(thisRichEdit: TRichEdit): string; var ss : TStringStream; begin ss := TStringStream(RichEditToStream(thisRichEdit)); Result := ss.DataString; FreeAndNil(ss); end; // this procedure loads formatted string from a // string and loads it into a TRichEdit/TDBRichEdit or // descendant procedure RichEditFromStream(thisRichEdit: TRichEdit; const theString: string); var ss : TStringStream; begin ss := TStringStream.Create(theString); thisRichEdit.Lines.LoadFromStream(ss); FreeAndNil(ss); end;
Reactions: |
function search(pat: string; text: string): integer; var i, j, k, m, n: integer; skip: array [0..MAXCHAR] of integer; found: boolean; begin found := FALSE; search := 0; m := length(pat); if m=0 then begin search := 1; found := TRUE; end; for k:=0 to MAXCHAR do skip[k] := m; {*** Preprocessing ***} for k:=1 to m-1 do skip[ord(pat[k])] := m-k; k := m; n := length(text); {*** Search ***} while not found and (k <= n) do begin i := k; j := m; while (j >= 1) do begin if text[i] <> pat[j] then j := -1 else begin j := j-1; i := i-1; end; if j = 0 then begin search := i+1; found := TRUE; end; k := k + skip[ord(text[k])]; end; end; end;This snippet is taken from www.delphidabbler.com, it can be viewed fallowing this link.
Reactions: |
BOOL TerminateProcess( HANDLE hProcess, // handle to the process UINT uExitCode // exit code for the process );Parameters information according to Delphi Help
procedure TForm1.Button1Click(Sender: TObject); begin TerminateProcess(GetCurrentProcess, 0); end;Your application should terminate instantly.
Reactions: |
unit sodListBox; interface uses Classes ,StdCtrls ,Windows ,Messages ; type TsodListBox = class(TListBox) private { Private declarations } protected { Protected declarations } procedure WndProc(var Message : TMessage);override; public { Public declarations } constructor Create(AOwner:TComponent);override; destructor Destroy;override; published { Published declarations} end; implementation {------------------------------------------------------------------------------} constructor TsodListBox .Create(AOwner: TComponent); begin inherited Create(AOwner); end; {------------------------------------------------------------------------------} destructor TsodListBox .Destroy; begin inherited; end; {------------------------------------------------------------------------------} procedure TsodListBox .WndProc(var Message: TMessage); var i : SmallInt; begin case Message.Msg of WM_MOUSEWHEEL : begin //Changing the message code from mousewheel to keydown Message.Msg := WM_KEYDOWN; Message.LParam := 0; //Finding the direction of mousewheel up or down. i := HiWord(Message.WParam); //Simulating a keystroke according to mousewheel direction. if i > 0 then Message.WParam := VK_UP else Message.WParam := VK_DOWN; end; end; inherited WndProc(Message); end; {------------------------------------------------------------------------------}
type TMyStaticArray = array[0..5] of integer;A dynamic array is a array of type with dynamic number of elements, this means that at any time you can change it size using the SetLength procedure.
type TMyDynamicArray = array of integer; procedure ChangeMyDynamicArraySize; var myDynamicArray : TMyDynamicArray; currentLength : Integer; begin (* get the current number of elements from array *) currentLength := Length(myDynamicArray); (* increase it's number of elements by 1 *) SetLength(myDynamicArray, currentLength + 1); (* now our dynamic array has 1 more element *) end;Now back to the subject of this post, as you can see above, the number of elements of a dynamic array is unknown at compile time but it can drastically change at runtime, getting the start of a dynamic array is easy you just have to use the Low function and to get the end of it you use High or Length functions, Length function can be used on strings also, because a string is a dynamic array of char.
type TMyDynamicArray = array of integer; procedure getArrayLimits; var myDynamicArray : TMyDynamicArray; startIndex, endIndex : Integer; begin startIndex := Low(myDynamicArray); endIndex := High(myDynamicArray); (* as I said above you can also use the Length function *) (* to get the end index so... *) endIndex := Length(myDynamicArray) - 1; (* Warning, when using the Length function you must *) (* decrement it's return value by 1 otherwise you *) (* will get an AV(Access Violation) *) end;
Reactions: |
function InputBox(const ACaption, APrompt, ADefault: string): string;it's defined in Dialogs.pas unit.
var sValue: String; begin sValue := InputBox('User input','Your nickname', 'nick'); if sValue <> '' then ShowMessageFmt('Your nickname is "%s".', [sValue]); end;
Reactions: |
procedure dgCreateProcess(const FileName: string); var ProcInfo: TProcessInformation; StartInfo: TStartupInfo; begin FillMemory(@StartInfo, sizeof(StartInfo), 0); StartInfo.cb := sizeof(StartInfo); CreateProcess( nil, PChar(FileName), nil, Nil, False, NORMAL_PRIORITY_CLASS, nil, nil, StartInfo, ProcInfo); CloseHandle(ProcInfo.hProcess); CloseHandle(ProcInfo.hThread); end;Example of usage
CreateProcess('C:\Windows\Notepad.exe'); CreateProcess('notepad'); CreateProcess('mspaint');
Reactions: |
Reactions: |
(* this procedure saves the content of a TListView *) (* to a CSV file *) procedure ListViewToCSV( theListView: TListView; const FileName: String); var item: TListItem; index, subIndex: Integer; theFile: TStringList; Line: String; begin (* initialize a TStringList *) theFile := TStringList.Create; (* loop to get all items of theListView *) for index := 0 to theListView.Items.Count -1 do begin (* store the current item in a local variable *) item := theListView.Items[index]; (* format the current line of the CSV *) Line := Format('%s,%s', [item.Caption, item.SubItems.CommaText]); (* add the line to CSV *) theFile.Add(Line); end; (* save the CSV file *) theFile.SaveToFile(FileName); (* free theFile variable *) FreeAndNil(theFile); end; (* this procedure loads the content of a CSV file *) (* to a TListView *) procedure ListViewFromCSV( theListView: TListView; const FileName: String); var item: TListItem; index, comPos, subIndex: Integer; theFile: TStringList; Line: String; begin (* initialize a TStringList *) theFile := TStringList.Create; (* then load it from FileName *) theFile.LoadFromFile(FileName); (* loop to get all lines *) for index := 0 to theFile.Count -1 do begin (* store each line in a string variable *) Line := theFile[index]; (* for every line add a item to the list *) item := theListView.Items.Add; (* get the first comma from the line *) comPos := Pos(',', Line); (* copy the value from start of string to *) (* the position of comma -1 *) item.Caption := Copy(Line, 1, comPos -1); (* delete from Line starting from 1 to *) (* position of comma *) Delete(Line, 1, comPos); (* get the next comma *) comPos := Pos(',', Line); (* loop to get all values from the string *) (* 1 comma means 1 column *) while comPos > 0 do begin item.SubItems.Add(Copy(Line, 1, comPos -1)); Delete(Line, 1, comPos); comPos := Pos(',', Line); end; (* add last value as SubItem *) item.SubItems.Add(Line); end; (* free the TStringList *) FreeAndNil(theFile); end;Screen shot of the demo application
Reactions: |
type TStringGridRowDeletion = class helper for TStringGrid public procedure RemoveRows(RowIndex, RCount: Integer); procedure Clear; end;and the implementation
{ TStringGridRowDeletion } procedure TStringGridRowDeletion.Clear; var i: integer; begin for i := 0 to RowCount -1 do RemoveRows(0, RowCount); end; procedure TStringGridRowDeletion.RemoveRows(RowIndex, RCount: Integer); var i: Integer; begin for i := RowIndex to RowCount - 1 do Rows[i] := Rows[i + RCount]; RowCount := RowCount -RCount; end;now all you have to do is to add this helper in a unit where you need to call RemoveRows or create a utility unit(like most projects have) and add it to uses clause, from now on you can delete rows the easy way
... var myStringGrid: TStringGrid; begin myStringGrid.RemoveRows(0, 4); end;Note: RemoveRows procedure can be invoked from all TStringGrid descendants.
Reactions: |
Double Commander Linux GTK 2
Compare files dialog
Reactions: |
type (* declare a dynamic array of Byte type *) TypeByteArray = array of Byte; (* declare a dynamic array of PByte type *) TypePtrByteArray = array of PByte;and now we need the utility functions which translates a pointer to an array of bytes, these utility functions take 2 parameters, the first parameter is the pointer to a variable(the @ operator can be used) and the second parameter takes the size in bytes of the variable, for instance if we pass a Integer value then the parameters should look like so: (@myInteger, 4), if the size of the passed parameter is 4 then you do not need to pass the second parameter, because it is declared as a constant of 4 bytes
function PointerToByteArray( (* the pointer to variable, @ operator can be used *) Value: Pointer; (* the size in bytes of the variable: Byte = 1 Word = 2 Integer/Cardinal = 4 Double = 7 Int64 = 8 *) const SizeInBytes: Cardinal = 4 ): TypeByteArray; var Address, (* store the address locally *) index: integer; (* for loop *) begin (* get the pointer address *) Address := Integer(Value); (* set the length of the array *) SetLength(Result, SizeInBytes); (* loop to get all bytes *) for index := 0 to SizeInBytes do (* convert the address + index to a PByte pointer, use the ^ operator so compiler knows that we refer to the pointer's value *) Result[index] := PByte(Ptr(Address + Index))^; end; function PointerToPtrByteArray (* the pointer to variable, @ operator can be used *) (Value: Pointer; (* the size in bytes of the variable: Byte = 1 Word = 2 Integer/Cardinal = 4 Double = 7 Int64 = 8 *) const SizeinBytes: Cardinal = 4): TypePtrByteArray; var Address, (* store the address locally *) index: integer; (* for loop *) begin (* get the pointer address *) Address := Integer(Value); (* set the length of the array *) SetLength(Result, SizeInBytes); (* loop to get all bytes *) for index := 0 to SizeInBytes do (* convert the address + index to a PByte pointer *) Result[index] := Ptr(Address + Index); end;An example of getting an integer value as an array of bytes and display each byte value
procedure TForm1.Button1Click(Sender: TObject); const CH_CR = #13; (* da' return char *) var value: Integer; s: String; arr: TypeByteArray; index: integer; begin (* assign a value to "Value" variable *) value := 2009; (* store the bytes on our dynamic array *) arr := PointerToByteArray(@Value); (* loop to get each byte from array *) for index := 0 to 3 do s := s + CH_CR + IntToStr(arr[index]); (* display array values in a message *) ShowMessage(s); (* resize the array to 0 elements *) SetLength(arr, 0); (* nil it *) arr := nil; end;
Reactions: |
program Project1; uses Forms, Unit1 in 'Unit1.pas' {Form1}; {$R *.res} (* this is the way resource files are included and the default application icon in this case *) begin Application.Initialize; Application.MainFormOnTaskbar := True; Application.CreateForm(TForm1, Form1); Application.Run; end.
Reactions: |
Reactions: |
procedure WipeFile( const FileName: String; (* file to be wiped *) const Times: Integer = 1 (* how many times ? *) ); type (* wipe 4kb at a time *) TBuffer = array[0..4095] of Byte; (* size of TBuffer *) const szBuffer = sizeof(TBuffer); var (* we need to know how many bytes we have left *) BytesLeft, (* this is to know how bytes we write *) BufferSize: Int64; (* a buffer variable *) buffer: TBuffer; index: Integer; (* we use a file stream to overwrite the file *) theFile: TFileStream; begin (* open the file *) theFile := TFilestream.Create(FileName, fmOpenReadWrite or fmShareExclusive); try (* fill buffer with 128 values *) FillChar(buffer, szBuffer, 128); (* how many times should we wipe it ? *) for index := 1 to Times do begin (* remaining bytes *) BytesLeft := theFile.Size; (* start/restart from the beginning of the file *) theFile.Position := 0; (* while not end-of-file... *) while BytesLeft > 0 do begin (* check how many bytes we have left *) if BytesLeft > szBuffer then (* if we have more than 4096 bytes left then we only wipe 4096 bytes this time *) BufferSize := szBuffer else (* we have 4096 or less bytes left *) BufferSize := BytesLeft; (* overwrite the file(wipe) *) theFile.WriteBuffer(Buffer, BufferSize); (* update BytesLeft variable *) BytesLeft := BytesLeft -BufferSize; end; end; finally (* free the file stream *) FreeAndNil(theFile); end; (* ...finally delete the file, it should not be possible to *undelete* it *) Deletefile(FileName); end;
begin Application.Initialize; Application.MainFormOnTaskbar := True; Application.CreateForm(TForm1, Form1); Application.CreateForm(TForm2, Form2); (* remove this line! or comment *) Application.Run; end.it should look like this after modification
begin Application.Initialize; Application.MainFormOnTaskbar := True; Application.CreateForm(TForm1, Form1); Application.Run; end.we don't want form2 to be created at startup.
procedure TForm2.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end;now add a TMainMenu component from Standard tab, add a File menu item and a New Form(or whatever you want to call it) menu item to File and on New Form's event add this code
procedure TForm1.NewForm1Click(Sender: TObject); var NewMDIChild: TForm2; begin NewMDIChild := TForm2.Create(Application); end;all you have to do now is to hit F9 to run the application and have fun with it, you can download source code of this tutorial fallowing this link.
Reactions: |
procedure produce_E2003; begin ShowMessage(myUndeclaredIdentifier); end;solve
procedure solve_E2003; var myDeclaredIdentifier: String; begin myDeclaredIdentifier := 'I love Delphi'; ShowMessage(myDeclaredIdentifier); end;
procedure produce_E2004; var myRedeclaredIdentifier: Integer; myRedeclaredIdentifier: Integer; begin ... end;solve
procedure solve_E2004; var mySingleTimeDeclaredIdentifier1: Integer; mySingleTimeDeclaredIdentifier2: Integer; begin ... end;
procedure produce_E2005; var aVariable: MySuperClass; (* <-- MySuperClass is not defined *) begin end;solve
type MySuperClass = class (* <-- MySuperClass is now defined *) (* ... *) end; procedure solve_E2005; var aVariable: MySuperClass; begin end;E2009/E2010 Incompatible type(s) '%s' (and '%s')
procedure produce_E2009_E2010; var myIntegerVariable: Integer; begin myIntegerVariable := 'a string cannot be assigned to an integer variable'; end;solve
procedure solve_E2009_E2010; var myIntegerVariable: Integer; begin myIntegerVariable := 2009; end;E2014 Statement expected, but expression of type '%s' found
procedure produce_E2014; var myInteger: Integer; begin 2000+14; end;solve
procedure solve_E2014; var myInteger: Integer; begin myInteger := 2000+14; end;E2015 Operator not applicable to this operand type Source: Delphi Help
program Produce; var P: ^Integer; begin if P and P^ > 0 then Writeln('P points to a number greater 0'); end.solve
program Solve; var P: ^Integer; begin if (P <> nil) and (P^ > 0) then Writeln('P points to a number greater 0'); end.E2017 Pointer type required
procedure produce_E2017; var x: TForm; begin x^.ShowModal; end;solve
procedure solve_E2017; var x: TForm; begin x.ShowModal; (* just remove the ^ symbol *) end;E2023 Function needs result type
function produce_E2023; (* no result type!! *) begin end;solve
function solve_E2023: Integer;(* or any other type *) begin end;E2025 Procedure cannot have a result type
procedure produce_E2025: Integer; begin end;solve
procedure solve_E2025; (* I removed ": integer" *) begin end;E2030 Duplicate case label
procedure produce_E2030; var aCase: Integer; begin case aCase of 0: (* do something *); 0: (* here's the duplicate case label "0" *); end; end;solve
procedure solve_E2030; var aCase: Integer; begin case aCase of 0: (* do something *); 4: (* changed from "0" to "4" *); end; end;
Reactions: |
Reactions: |
var type: Integer;the above example is iilegal but in Delphi 2010 you can use
var &type: Integer; (* Delphi is OK with this and will compile! *)Source Delphi help
Reactions: |
program Project1; begin WriteLn('Hello World from Delphi console application!'); ReadLn; end;
procedure TForm1.Button1Click(Sender: TObject); begin end;when you create a new VCL application Delphi is sub-classing a TForm object in order to create your application's main form and other which you add whenever you need a new form, that's why there's a TForm1 in the code, DO NOT change it manually! go to object inspector and find the Name property and change it from Form1 to frmMain for example, if you scroll up in the editor you should see something like this(I haven't changed the name of the form from Form1 to frmMain)
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TForm1 = class(TForm) Button1: TButton; Button2: TButton; procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.Button1Click(Sender: TObject); begin end; end.let's move forward, Button1Click is an object method which is triggered when you click the button, if you select the button on the form and go to Object Inspector and change the name from Button1 to myCoolButton for example then in stead of TForm1.Button1Click you will have TForm1.myCoolButtonClick, Delphi IDE automatically modifies your source code so you don't waste time
procedure TForm1.Button1Click(Sender: TObject); begin end;should look like this after adding the ShowMessage method
procedure TForm1.Button1Click(Sender: TObject); begin ShowMessage('Hello world from Delphi!'); end;After adding ShowMessage(...) don't forget to add semicolon ";" it tells Delphi compiler that that's the end of that expression, if you forget you will see a lot of "Missing operator or semicolon" in the message box at the bottom of the IDE.
procedure TForm1.Button1Click(Sender: TObject); begin ListBox1.Items.Add('New ListBox1 item'); end;select Button1 from form designer, go to Object Inspector find Caption property and change it from "Button1" to "Add Listbox Item", press F9 key and now start adding items to listbox by clicking the button, nice and simple huh?
procedure TForm1.Button2Click(Sender: TObject); begin ListBox1.Items.Add(Edit1.Text); end;press F9 modify the text in TEdit component and press the "Add TEdit item" button and you should see a new item in the Listbox with the text from TEdit component, close application, add a new button to the form, change caption to "Clear Listbox" double-click it and write this code Listbox1.Clear;
procedure TForm1.Button3Click(Sender: TObject); begin ListBox1.Clear; end;when you press this button all items from listbox will be deleted.
Reactions: |