C++Builder - Database tutorial, part 2In this part of our tutorial, we shall visualize the database by adding a "browser". Start by downloading the source code Articles2.zip and next unzip it to folder \CppProjects\Articles2. Database BrowserOpen project Articles2 in C++Builder and have a look at the form in Design mode. Note the TStringGrid component, named Grid, that is used for browsing the database. We set up the stringgrid at the start of the application, as can be seen here: void __fastcall TForm1::FormCreate(TObject *Sender)
{
// ... lines with old existing code
// ...
// New code:
Grid->ColWidths[0] = 60;
Grid->ColWidths[1] = 120;
Grid->ColWidths[2] = 80;
Grid->ColWidths[3] = 60;
Grid->Cells[0][0] = "ID";
Grid->Cells[1][0] = "Name";
Grid->Cells[2][0] = "Price";
Grid->Cells[3][0] = "Stock";
}
Each time a record is changed, this must be reflected in the TStringGrid. For this purpose, we added a
private method to the form, UpdateGrid() (see Unit1.h). void TForm1::UpdateGrid() { int index; Grid->RowCount = Articles->Count + 1; for (index = 0; index < Articles->Count; index++) { TArticle *Art = static_cast<TArticle*>(Articles->Objects[index]); Grid->Cells[0][index + 1] = Articles->Strings[index]; Grid->Cells[1][index + 1] = Art->Name; Grid->Cells[2][index + 1] = FormatFloat("0.00", Art->Price); Grid->Cells[3][index + 1] = IntToStr(Art->Stock); } } User friendlyWe made the application somewhat more user friendly. Therefore, we start off by hiding Panel1 and only show it when needed:
Improved searchingOur routine for finding an article by its ID is changed: instead of showing Panel1, it now highlights the line of the article in the stringgrid: void __fastcall TForm1::btnFindIDClick(TObject *Sender) { int index; if (Articles->Find(edFind->Text, index)) { stStatus->Caption = " Article was found "; Grid->Row = index + 1; Grid->SetFocus(); } else stStatus->Caption = " Article " + edFind->Text + " not found "; } Finally, we added a button for finding an article by its Name. void __fastcall TForm1::btnFindNameClick(TObject *Sender) { int index, posit; int foundwhere = -1; String S = edFind->Text; S = S.UpperCase(); // Find case-insensitive for (index = 0; index < Articles->Count; index++) { TArticle *Art = static_cast<TArticle*>(Articles->Objects[index]); Name = Art->Name; Name = Name.UpperCase(); // Find case-insensitive posit = Name.Pos(S); if (posit > 0) { foundwhere = index; break; // if found, break out of the loop } } if (foundwhere > -1) { stStatus->Caption = " Article was found "; Grid->Row = foundwhere + 1; Grid->SetFocus(); } else stStatus->Caption = " Article " + edFind->Text + " not found "; } |
|