Sunday, January 6, 2013

Selected Items of a TTreeView Component

Did you ever try to programmatically select a particular node in a TTreeView component? I thought this should be simple enough. Assuming that the particular node to be selected is given by Items[i] we could simply write the following statement:
TreeView1.Items[i].Selected := true;
Well that works; if we check whether the node is selected we get back a TRUE value. However the selection is not indicated visually, the display of the TTreeView component clears all previous selections, and that's all.... no indication of the new selection.

After hours of tedious experiments I finally found the solution: in order to make the component indicate the selection, you have to set the focus to the component (even if it already had the focus before selecting the node). So the following two-liner will do the job:

TreeView1.Items[i].Selected := true;
TreeView1.SetFocus;

2 comments:

  1. Thanks for this Hans; it's always great to get this sort of help.
    Chris Bargh

    ReplyDelete
  2. Thank you very much for this short, simple solution. This is exactly what I've been struggling with, and I think it would have taken quite some time to stumble across your solution.

    Doug Gardner

    ReplyDelete