I have 2 listboxes, the first listbox stores data pointers for each items Object property (defined by a custom class I have written). Whenever I select an item from this listbox, I populate the second listbox by accessing some of the data stored on the first listbox.
That is all good, but now I need to know how to save and restore the listboxes to XML.
I would appreciate it if someone could provide an example or assist me in writing the code to do this.
Here is some sample code to show how I create and access the data:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls;
type
TForm1 = class(TForm)
ListBox1: TListBox;
ListBox2: TListBox;
cmdAdd: TButton;
txtValue1: TEdit;
txtValue2: TEdit;
procedure cmdAddClick(Sender: TObject);
procedure ListBox1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
type
TMyData = class(TObject)
private
FValue1: String;
FValue2: String;
public
constructor Create(Value1, Value2: String);
property Value1: String read FValue1 write FValue1;
property Value2: String read FValue2 write FValue2;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
{ TMyData }
constructor TMyData.Create(Value1, Value2: String);
begin
inherited Create;
FValue1:= Value1;
FValue2:= Value2;
end;
procedure TForm1.cmdAddClick(Sender: TObject);
var
Obj: TMyData;
begin
Obj:= TMyData.Create(txtValue1.Text, txtValue2.Text);
Listbox1.AddItem(txtValue1.Text, Obj);
end;
procedure TForm1.ListBox1Click(Sender: TObject);
var
Obj: TMyData;
begin
ListBox2.Items.Clear;
Obj:= ListBox1.Items.Objects[ListBox1.ItemIndex] as TMyData;
ListBox2.Items.Add(Obj.Value2);
end;
end.
The most easy way to implement this is to start with the XML file. For example, build it up as follows:
Next, create an interface unit for this type of XML file by using the XML Data Binding Wizard, see File > New > Other > New > XML Data Binding. Tweak as you like, but simply passing every wizard page by clicking OK works just fine by default. (Note that the default settings for other Delphi versions might differ from that of mine.) Though the one thing I personally like to get rid of is the “Type” suffix for every interface type. (As well as for the class type names, but that’s not an option in the wizard, so you might do that manually.)
And now, to load and manipulate this XML file:
Update: This is the unit the wizard created here: