• 0

C# and making a TreeView out of arrays


Question

So I have encountered a probleem while trying to populate a TreeView control with nodes. I hope that there are a some kind people who t?ke the time and help me figuure out a correct solution.

So lets say I have 3 arrays:

 

["Example", "2", "1"]

{"Example", "2", "2"]

["Example", "3", "0"]

 

I know that my arrays have always exactly 3 elements in them, so the treeview will never have more than 3 childnodes

 

But all I am able to get is

 

Example

 2

  1

Example

 2

  2

Example

 3

  0

 

But the goal would be:

 

Example

 2

  1

  2

 3

  0

 

So where would I start chasing down the answer to my probleem?
Big thanks in advance :)

 

 

Recommended Posts

  • 0


void InitTreeView(List<string[]> arrays) {

            foreach (var array in arrays) {

                AddArray(array, 0, m_treeView.Nodes);

            }

        }

        /// <summary>

        /// Recursively adds each element of the array to the tree

        /// </summary>

        void AddArray(string[] array, int index, TreeNodeCollection nodes) {

            // Termination condition: we've past the bounds of the array

            if (index < array.Length) {

                var nextNode = AddValue(array[index], nodes);

                AddArray(array, index + 1, nextNode.Nodes);

            }

        }

        /// <summary>

        /// If the value exists, returns it, otherwise creates a new value

        /// </summary>

        TreeNode AddValue(string value, TreeNodeCollection nodes) {

            var index = nodes.IndexOfKey(value);

            if (index == -1) {

                var newNode = new TreeNode(value) { Name = value };

                nodes.Add(newNode);

                return newNode;

            }

            return nodes[index];

        }

  • 0

        private static TreeView GetTree(TreeView Tree, List<string[]> Items)
        {
            foreach (string[] item in Items)
            {
                TreeNode parent = new TreeNode();
                parent.Text = item[0];
                TreeNode child = new TreeNode();
                child.Text = item[1];
                TreeNode child2 = new TreeNode();
                child2.Text = item[2];
                child.Nodes.Add(child2);
                parent.Nodes.Add(child);
                Tree.Nodes.Add(parent);
            }
            return Tree;
        }

Well, I have a code  that goes through each array and creates parentnode with array first item, childnode with second and childnode of childnode with third. So thats pretty basic approach

 

  • 0

I imagine you want to do something like the following pseudo code.
Idea is that you create the array of children you want before you create the treenode with the label.

tv = new TreeView();
dict = new Dictionary<String, List<String>>();
arrs = array of those arrays;

for arr in arrs:
     dict[arr[1]].Add(arr[2]);

for (key, value) in dict:
    tv.Nodes.Add(new TreeNode(key, value.ToArray()))
  • 0
  On 22/12/2013 at 14:17, Lant said:

 

I imagine you want to do something like the following pseudo code.

Idea is that you create the array of children you want before you create the treenode with the label.

 

 

Got lost trying to implement something like that, although the approach is right, I need to create the last level nodes first

  • 0

What sort of performance are you looking for?  If you're just talking a few hundred items, then try this approach.

 

Each node should be identifiable via a predictable, unique key of your creation (it could be, literally, the value you're trying to insert).  Try to find your parent node by looking for the key it should have.  If you can't find it, create a new node and insert it.  If it returns something instead, then use that as the parent of the key you're trying to insert.

  • 0
  On 22/12/2013 at 16:55, jakem1 said:

Try a recursive function.

This is the right way to go, I know that, but I am totally unsure how the code should look like.

Regarding to performance, it is important in my case since we're talking about thousands of nodes here.

  • 0
  On 22/12/2013 at 17:01, ka-la said:

This is the right way to go, I know that, but I am totally unsure how the code should look like.

Regarding to performance, it is important in my case since we're talking about thousands of nodes here.

 

As a general rule of thumb, if you find yourself pushing program state into some sort of explicit stack when using an iterative solution (pushing state to a queue for example): you are may just be doing an explicit recursion (what I mean by this is that you are doing the same work that a recursion would do for you) and are may be better suited to just use a recursive solution.

  • 0

This should be very straightforward to convert to C#, but here's the general idea for a recursive solution:

InitTreeView:
    var data = new List<string[]> { " Your data here " };
    foreach array in data:
        AddArray(array, 0, root collection)

AddArray(array, index, nodes):
    // Termination condition: index is past the end of the array
    // Otherwise:
    nextNode = AddValue(array[index], nodes)
    AddArray(array, index + 1, nextNode collection)

AddValue(value, nodes):
    // If node exists in the collection, return it
    // Otherwise create new node with the value, add it and return it
  • 0
  On 26/12/2013 at 17:08, Andre S. said:

 

This should be very straightforward to convert to C#, but here's the general idea for a recursive solution:


InitTreeView:
    var data = new List<string[]> { " Your data here " };
    foreach array in data:
        AddArray(array, 0, root collection)

AddArray(array, index, nodes):
    // Termination condition: index is past the end of the array
    // Otherwise:
    nextNode = AddValue(array[index], nodes)
    AddArray(array[index], index + 1, nextNode collection)

AddValue(value, nodes):
    // If node exists in the collection, return it
    // Otherwise create new node with the value, add it and return it

Some parts of the code still remain as a puzzle for me:

1)  What should AddValue return, a collection or a treenode?

2) AddArray( array[index].... seems weird to me, it expects an array, but your code sends it a value from array with that index

3) What should AddArray return? my best guess so far is, it is just a void and does not return anything.

4) nextNode collection should be nextNode.Nodes ? (case the AddValue returns a treenode)

  • 0
  On 27/12/2013 at 15:08, ka-la said:

Some parts of the code still remain as a puzzle for me:

1)  What should AddValue return, a collection or a treenode?

2) AddArray( array[index].... seems weird to me, it expects an array, but your code sends it a value from array with that index

3) What should AddArray return? my best guess so far is, it is just a void and does not return anything.

4) nextNode collection should be nextNode.Nodes ? (case the AddValue returns a treenode)

1) As I wrote it, it returns a TreeNode. You could just return the collection as well as that's the only thing AddArray needs.

2) Oops that was a mistake, fixed. Should pass array.

3) AddArray is void.

4) Yup.

 

Is this homework?

  • 0
        private static TreeView GetTree(TreeView Tree)
        {
            Tree.BeginUpdate();
            List<string[]> l_tree = new List<string[]>();
            string[] str1 = new string[] {"Example", "2", "1"};
            string[] str2 = new string[] { "Example", "2", "2"};
            string[] str3 = new string[] { "Example", "3", "0" };
            l_tree.Add(str1);
            l_tree.Add(str2);
            l_tree.Add(str3);

            foreach (string[] array in l_tree)
            {
                AddArray(array, 0, Tree.Nodes);
            }
            Tree.EndUpdate();
            return Tree;
        }

        private static void AddArray(string[] array, int index, TreeNodeCollection nodes)
        {
            if (index < 3)
            {
                var nextNode = AddValue(array[index], nodes);
                AddArray(array, index + 1, nextNode.Nodes);
            }
        }

        private static TreeNode AddValue(string value, TreeNodeCollection nodes)
        {
            if (nodes.Count == 0)
            {
                TreeNode newnode = new TreeNode();
                newnode.Text = value;
                nodes.Add(newnode);
                return newnode;
            }
            else
            {
                foreach (TreeNode node in nodes)
                {
                    if (node.Text == value)
                    {
                        return node;
                    }
                    else
                    {
                        TreeNode newnode = new TreeNode();
                        newnode.Text = value;
                        node.Nodes.Add(newnode);
                        return node;
                    }
                }
            }
            return null;
        }

If the initial tree is empty, I get nullreferenceexception, since I cant go through the empty collection in addvalue

Example

 2

  1

    2

    0

  3

 

 

  • 0
  On 27/12/2013 at 22:59, ka-la said:

Sir I am truly thankful for your help, not sure how to return the regards :)

Glad to be of help. :) By the way, you can write this:

    List<string[]> l_tree = new List<string[]>();
    string[] str1 = new string[] {"Example", "2", "1"};
    string[] str2 = new string[] { "Example", "2", "2"};
    string[] str3 = new string[] { "Example", "3", "0" };
    l_tree.Add(str1);
    l_tree.Add(str2);
    l_tree.Add(str3);

more simply as:

    var l_tree = new List<string[]> {
        new[] { "Example", "2", "1" },
        new[] { "Example", "2", "2" },
        new[] { "Example", "3", "0" }
    }
  • 0

I haven't tested but are you required to use the new[] syntax for the string arrays(i.e. string[]) in this example or can you get away with removing that part because of the string type?

  • 0
  On 28/12/2013 at 02:56, snaphat (Myles Landwehr) said:

I haven't tested but are you required to use the new[] syntax for the string arrays(i.e. string[]) in this example or can you get away with removing that part because of the string type?

new[] { "a", "b" }

 is shorthand (since C# 3.0) for :

new string[] { "a", "b" }

There's also a special case (which was just to copy C/C++ in C# 1.0) for assignment to a new variable, where you can omit everything:

string[] array = { "a", "b" }

But then you have to explicitely type the variable, you can't use var. IMO this is old fashioned and for consistency everyone should write:

var array = new[] { "a", "b" }

Of course this works for all types and not just string.

  • 0
  On 28/12/2013 at 03:12, Andre S. said:
new[] { "a", "b" }

 is shorthand (since C# 3.0) for :

new string[] { "a", "b" }

There's also a special case (which was just to copy C/C++ in C# 1.0) for assignment to a new variable, where you can omit everything:

string[] array = { "a", "b" }

But then you have to explicitely type the variable, you can't use var. IMO this is old fashioned and for consistency everyone should write:

var array = new[] { "a", "b" }

Of course this works for all types and not just string.

 

 

Right, right, Is the special case for assignment still possible in newer C# revisions or is is not-recommended/depreciated? I initially thought that you were being a bit more verbose with the new[] statement in the compound list assignment because it was required. Sounds like you were doing it more for consistencies sake; which is fair.

  • 0
  On 28/12/2013 at 03:28, snaphat (Myles Landwehr) said:

Right, right, Is the special case for assignment still possible in newer C# revisions or is is not-recommended/depreciated? I initially thought that you were being a bit more verbose with the new[] statement in the compound list assignment because it was required. Sounds like you were doing it more for consistencies sake; which is fair.

I'm doing it in the list assignment because it is and has always been required in that case. You can omit new[] only if you assign the array expression to an explicitely typed variable. This, in addition to the fact that this syntax contradicts the usual C# principle that every expression has a type, makes it inconsistent and confusing in my eyes, but it's still supported. It's only my opinion and not any sort of official deprecation or recommendation.

  • Like 1
  • 0
  On 28/12/2013 at 03:56, Andre S. said:

I'm doing it in the list assignment because it is and has always been required in that case. You can omit new[] only if you assign the array expression to an explicitely typed variable. This, in addition to the fact that this syntax contradicts the usual C# principle that every expression has a type, makes it inconsistent and confusing in my eyes, but it's still supported. It's only my opinion and not any sort of official deprecation or recommendation.

 

Fair enough, I'll say that the bolded text is a good reason to use it in the above code regardless of opinion ;-)

  • 0
  On 28/12/2013 at 04:09, snaphat (Myles Landwehr) said:

Fair enough, I'll say that the bolded text is a good reason to use it in the above code regardless of opinion ;-)

I'm not sure if we're talking past each other... this:

new List<string[]> {
     { "a", "b", "c" },
     { "b", "c", "d" }
}

is not and never was legal C#.

This topic is now closed to further replies.
  • Posts

    • Wonder if the HDMI Forum will allow AMD to use HDMI 2.2 under Linux.
    • Where did you hear visio is discontinued? It's still available and being updated on Office 365 and even has an online free version now too.. and dont tell me because visio 2021 has EOL listed a Oct 13, 2026.. they have a beta version right now for visio 2026
    • PC gaming is stalling as well, recent analyst post I read is that it will stall for at least two years because of prices, tariffs and AI demand impacting GPU cost and availability. So far the only console to go up in price has been the Xbox. Which IMHO is just part of Microsoft’s plans to get out of the traditional insole market and move to a “Xbox” console that is just a PC made by an OEM with a Xbox sticker on it.
    • Jumping unicorns means people initiate Nintendo gaming
    • KB5060829: Microsoft makes Windows 11 File Explorer, Search faster with Build 26100.4482 by Sayan Sen Microsoft has released a new Release Preview build for Windows 11 Insiders. The new build, 26100.4482, under KB5060829, improves the performance of the File Explorer in case of extracting archives. The company says "has been enhanced when extracting archive files" and that the improvement will mainly be felt "in the case of copy pasting large numbers of files out of large 7z or .rar archives." Aside from File Explorer, Microsoft says that users can also expect a snappier Search. Microsoft notes that earlier the feature would respond "very slowly—the Search Box can take over 10 seconds to load before you can use it." Besides those, Taskbar has also received an improvement as it will better use the available real estate space more effectively with new ability to resize icons so more apps can fit. The build also brings new PC Migration tool. Start menu pins have also changed You can view the full changelog below: Gradual rollout [App defaults] New! We are rolling out some small changes in the EEA region for default browsers via the Set default button in Settings > Apps > Default apps: Additional file and link types will be set for the new default browser, if it registers them. The new default browser will be pinned to the Taskbar and Start menu unless you choose not to pin it by clearing the checkboxes. There is now a separate one-click button for browsers to change your .pdf default, if the browser registers for the .pdf file type. [Start menu] New! For Admins, the Configure Start Pins policy now includes an option to apply Start menu pins only once. This means users will receive the admin Start menu pins on their first sign-in (day 0), but afterward, they can personalize their pinned layout, and those changes will be retained. This policy can also be applied through group policy, in addition to the existing configuration service provider (CSP) method. [Taskbar & System Tray] New! The taskbar now resizes icons to fit more apps when space runs low, keeping everything visible and easy to access. You can adjust how icons appear in settings—reduce icon size only when the taskbar is full (default), keep icons at their original size at all times by selecting Never, or use smaller icons all the time by selecting Always. To change this setting, right-click an empty area on the taskbar, select Taskbar settings, expand the Taskbar behaviors section, and choose your preference under Show smaller taskbar buttons. New! In addition to the new grouping of the Accessibility menu in Quick settings, there are text descriptions for the assistive technologies like Narrator, Voice access, and more for easier identification and learning. New! Adjusted the indicator (pill) under taskbar apps to make it wider and more visible. Fixed: Clicking the top third of the buttons in the top row doesn’t work to enable or disable the button. Fixed: WIN + CTRL + Number doesn’t work anymore for switching windows of an open app in the taskbar Fixed: When using taskbar in Windows, the media controls that appear in the preview windows for apps might unexpectedly flicker. [Windows Share] New! When you share links or web content using the Windows share window, you will see a visual preview for that content. New! In the Windows share window, you can select a compression level—High, Medium, or Low Quality—when editing and sharing images, instead of selecting from a 0–100 scale. [PC Migration] We’re beginning the rollout of a new PC-to-PC migration experience in Windows. You’ll start to see the landing and the pairing page in the Windows Backup app, giving you a first look at what’s coming. In the full experience, you will be able to transfer your files and settings from your old PC to the new one during the PC setup process. Support during the PC setup will be available in a future update. We are releasing in phases for a smooth experience and will provide more details soon. [File Explorer] Improved: Performance has been enhanced when extracting archive files – this will particularly help in the case of copy pasting large numbers of files out of large 7z or .rar archives. Narrator New! The Screen Curtain feature in Narrator helps protect your privacy and improve focus by blacking out the screen while Narrator reads content aloud. This is especially helpful in public or shared spaces, where you can work with sensitive information without others seeing your screen. To turn on Narrator, press Ctrl + Windows + Enter. Then press Caps Lock + Ctrl + C to enable Screen Curtain. While it’s on, you can use Narrator as usual with the screen hidden. Press Caps Lock + Ctrl + C again to turn it off. New! Narrator makes it easier to discover and learn about its features directly within the experience. Whether you’re new or exploring advanced options, Narrator will guide you through the latest updates using a series of steps and prompts that explain each new feature and change. [Voice Access] New! You can now use voice access to navigate, dictate, and interact with Windows using voice commands in Simplified Chinese and Traditional Chinese. New! You can add custom words to the dictionary in voice access. The feature will be available in all the currently supported voice access languages. [Settings] New! The Settings homepage on PCs managed by IT administrators now includes cards tailored for enterprise use. These include familiar options like “Recommended settings” and “Bluetooth devices,” along with two cards for device info and accessibility preferences. If a user signs in with both a work or school account and a Microsoft account, an additional accounts card appears to show both account types. New! Added the country or region selected during device setup under Settings > Time & language > Language & region. Fixed: The storage card in Settings > System > About shows an incorrect or unreadable character instead of the proper disk size. [Windowing] Fixed: When you ALT + Tab out of a full screen game, other windows (like Windows Terminal might stop responding. Fixed: An underlying issue might lead to unexpected window size and position changes after sleep/resume for some devices. Fixed: Explorer.exe might stop working unexpectedly when dragging a window if window snapping is enabled. [Scripting] Fixed: Running a script on a remote SMB share might take an unexpectedly long time if the share was an older Windows Server version like Windows Server 2019. [Graphics] Improved: Made some underlying changes to help improve display related user experiences, including reducing screen flashing in some display configuration transitions and removing unnecessary display resets which was happening in some cases. Fixed: Certain displays might be unexpectedly green. Fixed: If User Account Control (UAC) is set to Always Notify and the button under Settings > System > Display for color calibration is selected for your display and canceled, Settings will stop responding. [Color Filters] Improved: Adjusted the location of the intensity and color boost sliders under Settings > Accessibility > Color Filters, so the color previews at the top of the page are visible while adjusting the sliders. [Input] Fixed: Typing Japanese with the touch keyboard may stop working after switching to typing with an English keyboard and back. [Printing] Fixed: Printed lines might be unexpectedly thicker than expected. [MSFTEdit.dll] Fixed: Some apps like Sticky Notes and dxdiag might stop working when the display language is set to Arabic or Hebrew. Normal rollout [Copilot] Fixed: Improved the Copilot key’s reliability and resolved an issue that prevented users from restarting Copilot after using the key. [Performance] Fixed: This update addresses an issue to maintain efficiency of Storage Spaces Direct (S2D). When running complex software defined data center (SDDC) related workflows, it’s possible the system might become unresponsive. [Storage optimization] Fixed: An issue that prevented unused language packs and Feature on Demand packages from being fully removed, which led to unnecessary storage use and longer Windows Update installation times. [Windows Search] Fixed: Windows Search responds very slowly—the Search Box can take over 10 seconds to load before you can use it. Fixed: This update enhances the reliability of Windows Search and resolves an issue that prevented users from typing in Windows Search in some cases. You can find the official blog post here on Microsoft's website.
  • Recent Achievements

    • Week One Done
      Wayne Robinson earned a badge
      Week One Done
    • One Month Later
      Karan Khanna earned a badge
      One Month Later
    • Week One Done
      Karan Khanna earned a badge
      Week One Done
    • First Post
      MikeK13 earned a badge
      First Post
    • Week One Done
      OHI Accounting earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      690
    2. 2
      ATLien_0
      264
    3. 3
      Michael Scrip
      201
    4. 4
      +FloatingFatMan
      167
    5. 5
      Steven P.
      137
  • Tell a friend

    Love Neowin? Tell a friend!