How to cast selected TListViewItem from "OnItemClick" event, on assigning to multiple buttons?

268 Views Asked by At

i have an application with 2 TButton, 1 TListView. I would like display the value or content(Text) of TListViewItem inside the TButton(s) in a way that the content of the first TButton can't be the same with the 2nd one. Steps =>>

  1. When I click on the 1st TButton, I can select the Item text in the TListView and save it as new TButton text.

  2. When I click on the 2nd TButton, I can select another item text in the same TListView, and it is saved as Text in the 2nd TButton.

My code:

....
  ListView1: TListView;
  Base: TButton;
  Hypo: TButton;
....

procedure TMainForm.BaseClick(Sender: TObject);
begin
   ListView1.Visible := True;
end;

procedure TMainForm.HypoClick(Sender: TObject);
begin
   ListView1.Visible := True;
end;    

procedure TMainForm.ListView1ItemClick(const Sender: TObject;
   const AItem: TListViewItem);
begin
   if Assigned(ListView1.Selected) and Assigned(Base.OnClick) then
   begin
      Base.Text := TListViewItem(ListView1.Selected).Text;
   end else
   if Assigned(ListView1.Selected) and Assigned(Hypo.OnClick) then
   begin
      Hypo.Text := TListViewItem(ListView1.Selected).Text;
   end;
   ListView1.Visible := False;
end;

I used LiveBindings to fill the TListView; when i run the app and select one item it works but it's displaying the same value/content in both TLabels TListViewwith2labels

2

There are 2 best solutions below

6
SergeGirard On

My first reaction, if your listview is livebinded then why don't you use livebindings to link your 2 labels ?

Second one is your code, you use Selected when you have the AItem parameter so

procedure TMainForm.ListView1ItemClick(const Sender: TObject;
   const AItem: TListViewItem);
begin
  Base.Text:= AItem.text;
  Hypo.Text:= AItem.detail;
  ListView1.Visible := False;
end;  

should be sufficient if it is not a DynamicAppearance type.

2
SergeGirard On

If you really have 2 selected items, then you have to iterate through the whole list view

procedure TForm3.ListView1ItemClick(const Sender: TObject;
  const AItem: TListViewItem);
var elvitem : TListViewItem;
    i,n : integer;
begin
n:=0;
for i:=0 to ListView1.ItemCount-1 do
 begin
   if ListView1.Items[i].Purpose=TListItemPurpose.None then // it's an item 
    begin
      if ListView1.Items[i].Checked then
      begin
       inc(n);
      case n of
        1 : base.text:=ListView1.Items[i].Text;
        2 : begin
              hypo.text:=ListView1.Items[i].Text;
              break; // don't search more
            end;
      end;
      end;
    end;
 end;

Here item 2 and 8 are selected with this code

procedure TForm3.FormCreate(Sender: TObject);
begin
Listview1.Items[2].Checked:=True;
Listview1.Items[8].Checked:=True;
end;

here item 2 and 8 are selected