XtraTreeList: Which element in my IList<> is selected?

Let us look at some common means that different frameworks use to deliver a result to this question.

As I mentioned before, I mostly used the standard .NET components or VCL controls. Data-based VCL controls can be bound to TDataSource (and derivatives due to polymorphism). If an item is being selected, the cursor in the source moves accordingly. Thus, there is no difficulty to determine which row in the dataset it selected as it is the current row of the dataset.

.NET uses a different system of databinding, especially as you can bind - as I tend to say, but please do not take it literally - anything to a control. It is very flexible in that regard. Let us not even consider the possibilities that arise due to WPF.

In my last blog post I bound an XtraTreeList to a datasource of the datatype List<>. Any .NET standard control implements some kind of CurrencyHandler, which I find a bit too complex to use for a simple “Tell me what is selected”. Thus, I like ECO very much that it delivers a means to determine a selected object in a list of objects via its CurrencyManagerHandle. It always points to the selected object and you have a reference you can work with.

Now to XtraTreeList. In my example it is bound to a datasource that implements the IList interface. From reading the documentation I found out that it is very important that there is a difference between focused and selected row. Be aware that these terms play a major role which also depends on the fact if your list allows multi-selection or not.

In this case, we do not have multi-selection, thus the property we are interested in is called FocusedNode. The object instance we get as a return value is not of the element type of the list we bound to. Very unlucky. So, we need to investigate the return type. IntelliSense immediately offers “Id” as a property that looks like we could use.

In my example I query it like this:

[code lang="c#"]
int id = trFolders.FocusedNode.Id;
[/code]

The Id designates the index of the element inside the element list we bound to. Excellent. I wonder why it is not named accordingly, but it is something I can live with :-)

This leads to my final implementation to get the selected FolderTreeItem in my example:

[code lang="c#"]
public FolderTreeItem SelectedFolderTreeItem
{
get
{
int id = trFolders.FocusedNode.Id;
FolderTreeItem selectedItem = dataSource[id];
return selectedItem;
}
}
[/code]

I hope this will be helpful for people as all the examples delivered with XtraTreeView I could find do not deliver an example for this. I am not saying they do not exist, but they were too hard for me to find. Furthermore, I am still used to the other means to get the selected object and can be considered “user at a basic stage” regarding the DX control set.

Tags: ,