My programs run like this:
The following should teach you all the ingredients you need.
Create a new application. I chose to make a VCL application, but I double-checked that all the steps are the same in Firemonkey (FMX).
Add a few edit boxes and combo boxes, like this:
Name the controls eFirstName
, eLastName
, cbSex
, and btnSave
, respectively.
Then write the following OnClick
handler for the button:
procedure TForm1.btnSaveClick(Sender: TObject);
var
DataFile: TMemIniFile;
begin
DataFile := TMemIniFile.Create(TPath.Combine(TPath.GetDocumentsPath, 'PersonalData.txt'));
try
DataFile.WriteString('General', 'FirstName', eFirstName.Text);
DataFile.WriteString('General', 'LastName', eLastName.Text);
if cbSex.ItemIndex <> -1 then
DataFile.WriteString('General', 'Sex', cbSex.Items[cbSex.ItemIndex]);
DataFile.UpdateFile;
finally
DataFile.Free;
end;
end;
You need to add both IniFiles
and IOUtils
to your uses
list (at least the implementation
one).
Now, if you fill in the form,
and click the Save
button, the following file is created:
[General]
FirstName=Andreas
LastName=Rejbrand
Sex=Male
It isn't evident from the screenshots alone, but if you are at the top edit box and press the Tab key repeatedly, you go to the second edit box, to the combo box, and then, finally, to the button. This is because I made sure that the tab order is correct. You should do the same.
Also notice the underlined characters. These are called keyboard accelerators. If I press Alt+F, for instance, focus will move to the First name
field. This is achieved by giving the label the caption (text) &First name:
and assigning the corresponding edit control to the label's FocusControl
property.
In this case, the button is Default
, meaning that it is the button that responds to the Enter key. If it hadn't been default (and in your GUI, that might not make sense), I would have given it the caption &Save
and changed &Sex:
to S&ex:
. Can you guess why?
You can also use a TStringList
:
procedure TForm1.btnSaveClick(Sender: TObject);
var
DataFile: TStringList;
begin
DataFile := TStringList.Create;
try
DataFile.AddPair('FirstName', eFirstName.Text);
DataFile.AddPair('LastName', eLastName.Text);
if cbSex.ItemIndex <> -1 then
DataFile.AddPair('Sex', cbSex.Items[cbSex.ItemIndex]);
DataFile.SaveToFile(TPath.Combine(TPath.GetDocumentsPath, 'PersonalData.txt'),
TEncoding.UTF8);
finally
DataFile.Free;
end;
end;