tags:

views:

143

answers:

2

I have one record type. I want to add the variable of that record type in TListbox and retrieve it on click event of TListbox. Is it possible? If yes then how?

I added it using

lstbox.AddItem(data,myrec);

It shows error of incompatible types. data is string and myrec is variable of MyRecord which I have created.

For adding:

New(fptr1);
ZeroMemory(fptr1,sizeof(fptr1^));
fptr1^ := fptr^;
lstboxLeft.AddItem(path,TObject(fptr1));

For retrieve:

fptr := PData(lstboxLeft.Items[lstboxLeft.ItemIndex]);
+6  A: 

AddItem takes a TObject as the second parameter and a record is not an object. You could either make your record a TObject instead (usually the best solution) or cast the record to an object.

Here is a working example using records:

type
  PMyRec = ^TMyRec;
  TMyRec = record
    I : integer;
  end;

procedure TForm1.FormCreate(Sender: TObject);
var
  P : PMyRec;
begin
  New(P);
  P.I := 42;
  ListBox1.AddItem('One',TObject(P));
end;

procedure TForm1.FormDestroy(Sender: TObject);
var
  I : integer;
begin
  //Free memory
  for I := 0 to ListBox1.Items.Count - 1 do
    Dispose(PMyRec(ListBox1.Items.Objects[I]));
end;

procedure TForm1.ListBox1Click(Sender: TObject);
var
  P : PMyRec;
begin
  P := PMyRec(ListBox1.Items.Objects[ ListBox1.ItemIndex ]);
  ShowMessage( IntToStr(P.I) );
end;
Ville Krumlinde
@VilleK and how to access it again?
Himadri
@VilleK Its not giving me value. It gives garbage value. I am using Delphi 2007
Himadri
You are probably not handling the memory management correctly. Instead of declaring a TMyRecord locally in a method when adding items, declare a PMyRecord and initialize it using new (see answer by SimaWB). When you are finished with the listbox loop through the items and call dispose to free memory again.
Ville Krumlinde
@VilleK I am doing the same as you are saying
Himadri
There are several pitfalls with using records this way so perhaps you would be better off using a TObject instead. Please update your question with the code you have problem with so it will be easier for us to help.
Ville Krumlinde
@Villek updated
Himadri
Ville, it looks like you're adding a pointer to a local variable. You should dynamically allocate the memory as shown in Sima's answer and now in the question.
Rob Kennedy
@Rob: You are right. I've updated my answer.
Ville Krumlinde
Thank you so much. Now it's doing exactly what I wanted
Himadri
+2  A: 
Type    
  PMyrec = ^MyRecord;
var
  MyRec : PMyRec;  
begin
  new(MyRec);
  //fill MyRec 
  lstbox.AddItem(data, TObject(myrec));

  //Dispose
SimaWB