kopaty4
kopaty4

Reputation: 2296

Delphi Listbox Item name, no caption

I add items to listbox:

for i:=0 to HomeWorkers.Count-1 do
begin
s := '['+HomeWorker[i].Id+']  ' + HomeWorker[i].Name;
Listbox1.Items.Add(s);
end;

Now i want to get number of selected item. I can get its caption:

ShowMessage(ListBox1.Items.Strings[Listbox1.ItemIndex]);

Example id`s: 12880345, 1274136. Can I add Item with

'['+HomeWorker[i].Id+']  ' + HomeWorker[i].Name;

, but in ShowMessage display only HomeWorker[i].Id without string caption parsing? Thanks in advance. P.S I am from Russia, so sorry for bad English

Upvotes: 2

Views: 6135

Answers (3)

Karraksc
Karraksc

Reputation: 1

Maybe this might answer his question, if I am getting it right? He is pulling the item in his example, when he should be showing his object instead.

Try this:

showmessage(string(listbox1.items.object[listbox1.itemindex]));

in place of:

ShowMessage(ListBox1.Items.Strings[Listbox1.ItemIndex]);

Upvotes: 0

Ondrej Kelle
Ondrej Kelle

Reputation: 37221

You could store the IDs in the Objects property, just typecast from Integer to TObject:

ListBox1.Items.AddObject(Format('[%d] %s', [Homeworker.ID, Homeworker.Name]),
  TObject(Homeworker.ID));

and later you can retrieve it, typecasting back:

ShowMessage(IntToStr(Integer(ListBox1.Items.Objects[ListBox1.ItemIndex])));

Upvotes: 5

David Heffernan
David Heffernan

Reputation: 613511

As I understand your question, you want to extract the Id from the formatted text that you put into the list box. If I'm correct, you can do it like this:

function GetIdFromListBoxText(const Text: string): string;
var
  P1, P2: Integer;
begin
  P1 := Pos('[', Text);
  P2 := Pos(']', Text);
  if (P1<>0) and (P2<>0) then
    Result := Copy(Text, P1+1, P2-P1-1)
  else
    Result := '';
end;

This code relies on an assumption that your Id strings do not contain [ or ].

You can use it in your code like this:

ShowMessage(GetIdFromListBoxText(ListBox1.Items[Listbox1.ItemIndex]));

Upvotes: 1

Related Questions