Delphi – Execute event only if a treeview node is clicked

delphitreeview

I, (more time), trying to execute action when i click into a item of a treeview see:

procedure TForm1.TreeView1Click(Sender: TObject);
begin

  if treeview1.Selected.AbsoluteIndex=1 then
  begin
    showmessage('selecionado');
  end; 

end;

This code show a message if user click into index 1 of a treeview, The problem is the following: If the user selects the index 1, the message will be shown, however after that, the user click into empty area of the listview the message is still performed because the item is still selected. How can I make the event run only if the User clicks the corresponding item?

Best Answer

Don't use OnClick, which occurs whenever the TTreeView is clicked (not only when a node is clicked). Instead, use the TTreeView.OnChange event, which passes you the node:

procedure TForm3.TreeView1Change(Sender: TObject; Node: TTreeNode);
begin
  if Assigned(Node) then
    if Node.AbsoluteIndex = 1 then
      ShowMessage('selecionado');
end;
Related Topic