C++ Builder Examples Collection: 50 Practical Projects for Beginners

C++ Builder Examples Collection — GUI, Database & Networking SamplesC++ Builder remains a productive environment for building native Windows (and cross-platform with RAD Studio) applications using a visual designer, component library, and tight integration with the underlying C++ language. This article collects practical, well-explained examples across three major domains you’ll commonly encounter when using C++ Builder: GUI (user interface) development, database integration, and networking. Each section includes goals, step-by-step guidance, code snippets, and tips for extension and debugging so you can adapt the examples to real projects.


Why these three areas matter

  • GUI is how users interact with your application; effective GUI examples accelerate development and usability.
  • Database access is central to business apps, persistence, and data-driven features.
  • Networking enables distributed apps, APIs, real-time data, and communication between systems.

Together they cover the bulk of typical desktop application requirements.


Assumptions and setup

  • Examples target C++ Builder (RAD Studio) 10.x and later; adjust minor API differences if using an older version.
  • You should be familiar with the IDE, form designer, components palette, and basic C++ syntax.
  • Where code interacts with the VCL (Visual Component Library) or FireMonkey (FMX), I’ll call out which framework is used.
  • For database samples we’ll use FireDAC (modern, recommended database framework). For networking, examples use Indy components and cross-platform FireMonkey networking where applicable.
  • Error handling is shown in concise form; production code should include more robust error checks, logging, and resource management.

GUI Examples (VCL and FMX)

1) Simple CRUD form (VCL) — Master-detail with TDBGrid and TDataSource

Goal: Create a basic data-entry form that lists records in a grid and allows add/edit/delete.

Steps:

  1. Create a VCL Forms Application.
  2. Drop a TFDConnection (FireDAC) and configure connection parameters to your database (SQLite, MySQL, MSSQL, etc.).
  3. Add a TFDQuery for the master dataset and a TDataSource. Set TDBGrid.DataSource to the data source.
  4. Add TButton components for Add, Edit, Delete, and Save. Use a TFDQuery or TFDMemTable for in-memory editing.

Key code snippet (simplified — VCL event handlers):

void __fastcall TForm1::BtnAddClick(TObject *Sender) {     FDQuery1->Append();     // Open an editor form or enable fields for inline editing } void __fastcall TForm1::BtnDeleteClick(TObject *Sender) {     if (!FDQuery1->IsEmpty()) {         FDQuery1->Delete();         FDQuery1->ApplyUpdates();     } } 

Tips:

  • Use TFDMemTable for disconnected scenarios.
  • Use TDataSource.State to control UI enablement.
  • Use transactions for grouped updates.

2) Modern FMX responsive UI — Dynamic controls and styles

Goal: Build a responsive form that creates controls at runtime and applies styles.

Steps:

  1. Create a Multi-Device Application (FireMonkey).
  2. Use TLayout, TScrollBox, and stylebook to design responsive UI.
  3. Dynamically create TButton or TLabel instances and position them relative to parent size.

Code snippet:

void __fastcall TForm1::CreateDynamicButtons(int count) {     for (int i = 0; i < count; ++i) {         TButton *b = new TButton(this);         b->Parent = DynamicLayout;         b->Text = "Button " + IntToStr(i+1);         b->Align = TAlignLayout::Top;         b->Margins->Top = 4;         b->OnClick = ButtonClick;     } } 

Tips:

  • Use anchors and alignments for auto-layout.
  • Use styles to change appearance across platforms.

3) Drag-and-drop list reordering (VCL)

Goal: Let users reorder items in a listview by dragging.

Approach:

  • Use TListView or TListBox; handle OnMouseDown, OnMouseMove, and OnMouseUp to start/stop dragging.
  • Use BeginDrag/EndDrag and OnDragOver/OnDragDrop to reposition items.

Concise logic:

  • Store index of source item on mouse down.
  • On drop, remove and insert item at target index, then refresh.

Database Examples (FireDAC)

4) Connect to SQLite and run parameterized queries

Goal: Show a lightweight local DB with parameterized selects/inserts.

Setup:

  • Add TFDConnection (DriverName = SQLite), set Database value to a file path.
  • Add TFDQuery, set Connection to the TFDConnection.

Example: parameterized select and insert

FDQuery1->SQL->Text = "SELECT id, name, email FROM users WHERE name LIKE :pattern"; FDQuery1->ParamByName("pattern")->AsString = "%John%"; FDQuery1->Open(); FDQuery1->SQL->Text = "INSERT INTO users (name, email) VALUES (:name, :email)"; FDQuery1->ParamByName("name")->AsString = "Alice"; FDQuery1->ParamByName("email")->AsString = "[email protected]"; FDQuery1->ExecSQL(); 

Tips:

  • Use prepared statements for performance: FDQuery1->Prepared = true;
  • Use TFDMemTable to manipulate rows in-memory, then use TFDUpdateSQL/ApplyUpdates.

5) Multi-tier access with DataSnap / RAD Server (overview)

Goal: Outline how to expose database services securely to clients.

Approach:

  • Server: create DataSnap or RAD Server endpoints that execute queries and return datasets or JSON.
  • Client: use REST components (TNetHTTPClient/TRESTClient) or DataSnap client components to call methods.

Security:

  • Use HTTPS, token-based auth, and parameterized queries to avoid SQL injection.

Networking Examples

6) Simple HTTP client using Indy (TIdHTTP)

Goal: Fetch JSON from a REST API and parse it.

Steps:

  1. Drop TIdHTTP and optionally TIdSSLIOHandlerSocketOpenSSL for HTTPS.
  2. Call Get or Post and parse the result with a JSON library (System::JSON).

Code:

String url = "https://api.example.com/items"; try {     String resp = IdHTTP1->Get(url);     TJSONObject *j = (TJSONObject*)TJSONObject::ParseJSONValue(resp);     // process JSON...     delete j; } catch (const Exception &e) {     ShowMessage("HTTP error: " + e.Message); } 

Tips:

  • Set IdHTTP1->Request->UserAgent and timeouts.
  • Handle SSL libraries on Windows: ship OpenSSL DLLs or use platform SSL providers.

7) TCP client-server with Indy (TIdTCPServer / TIdTCPClient)

Goal: Build a basic request-response server for a custom protocol.

Server-side (pseudocode):

  • Drop TIdTCPServer, set DefaultPort, implement OnExecute to read lines and write responses.

Client-side:

  • Use TIdTCPClient, Connect(), IOHandler->WriteLn(), IOHandler->ReadLn().

Example server handler:

void __fastcall TForm1::IdTCPServer1Execute(TIdContext *AContext) {     String req = AContext->Connection->IOHandler->ReadLn();     String resp = "Echo: " + req;     AContext->Connection->IOHandler->WriteLn(resp); } 

Notes:

  • Use threadsafety for shared resources.
  • Consider TLS (IdServerIOHandlerSSLOpenSSL) for encryption.

Cross-cutting concerns and best practices

  • Threading: Use TTask, TThread, or Indy’s threaded model for long-running I/O. Always synchronize UI updates with TThread::Synchronize or TThread::Queue.
  • Exception handling: Wrap database and network calls in try/catch and surface friendly messages to users.
  • Resource cleanup: For objects created at runtime, use try/finally or smart pointers (std::unique_ptr) to avoid leaks.
  • Security: Use parameterized queries, validate all network inputs, and use secure transport (TLS).
  • Testing: Write small unit tests around business logic; separate UI from logic so core functions are testable.

Example project ideas to practice these samples

  • Address book: GUI with CRUD (FireDAC + SQLite), export/import CSV, simple sync via HTTP REST.
  • Chat app: Indy TCP server + FMX client using TLS, message history stored in database.
  • Inventory manager: Master-detail lists, reports, and scheduled sync to central server via REST.
  • Remote sensor dashboard: FMX real-time charts connected to a WebSocket or polling REST endpoint.

Debugging tips

  • Enable FireDAC tracing to see SQL and parameter values when troubleshooting.
  • Use the IDE’s debugger to inspect dataset fields and component properties at runtime.
  • For networking issues, use Wireshark or Fiddler to inspect traffic, and log raw requests/responses.

Further reading and resources

  • FireDAC documentation for connection pooling, batch updates, and advanced fetch options.
  • Indy documentation and examples for secure communications and protocol handling.
  • VCL and FMX style guides for consistent cross-platform UI.

This collection provides templates and practical code for building desktop applications with common real-world features. Integrate these snippets into larger projects, expand error handling and validation, and adapt architectures (MVC/MVVM) to keep UI, data, and logic cleanly separated.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *