Articles

Programmatically Type Casting a TreeNode in Kentico

Programmatically typing casting a TreeNode in Kentico is not something that is readily available on the internet. In fact, when someone posed just such a question in the Kentico forums, they were met with "why would you do that?".

This code examples takes a few liberties in the assumptions being made.

  1. You already have a valid TreeNode from the DocumentHelper or generated Provider
  2. You are type casting to the generated pages model exported from Kentico (in this case assumed to be YourPageType)
var node = ...; // set your tree node or nodes
var typedNode = TreeNode.New<Generated.Pages.YourPageType>(node.GetDataSet().Tables[0].Rows[0]);

That's it!

Why would you want to do this? Well in some scenarios you might need to return a list of tree nodes that are a mix of different types, as it can be more efficient to manipulate the items in code, vs doing something like a N+1 query.

In this case, it would be nice to still work with the strongly typed generated classes. Now you can.

Back to articles
Back to top