• 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

    • WhatsApp beta users can now craft their own AI chatbots - here's why you might want one by Paul Hill Since the end of 2022, tech companies, and even non-tech companies, have been clamoring to pile AI into their services. Despite what many people say about not liking AI, plenty of people are still using it every day, making it a key offering. Not only that, but for public companies like Meta, the inclusion of AI does very well with investors, so that’s another reason it’s being added. While the most common chatbot people talk about is ChatGPT, which is pretty faceless, there is demand for AI chatbots with a face, this is why people use tools like Character.ai and Replika. One of the only big tech firms that has gone down this route is Meta, which lets you create and share AI characters. To date, some of Meta’s apps, like Messenger, allow you to chat with these AI personas but you can’t do that yet in the stable version of WhatsApp. The company is now testing it with the Android Beta and when it’s ready, it should make a more seamless experience across Meta’s applications. Many of the popular bots that people use including ChatGPT, Gemini, and DeepSeek are faceless and offer the same tone out of the box. To be fair to Gemini, it does allow all users to create Gems now, and they actually offer a bit more flexibility than just creating characters to talk to like in Messenger. The chatbots in Messenger have the benefit of being in the Messenger app, which most people use and giving them a personality and making them feel like an “AI person” fits better in Messenger. Whether we really need these AI bots in Messenger is still up for debate. It’s quite a new feature and some people may find some good uses for them, but as mentioned, they don’t seem as flexible, or provide as detailed responses as custom bots made on Poe or Gemini Gems. They are definitely for having casual conversations with. WhatsApp's new AI chatbot creator We’ve known that the chatbot feature was coming to WhatsApp for a long time already. WhatsApp beta for Android 2.25.1.26, released in January, included the feature for some beta testers. With the latest WhatsApp beta for Android 2.25.18.4, it seems like WhatsApp is trialing the feature with members of the public, suggesting its release is imminent. Screenshots of the app, obtained by WABetaInfo show that you can describe your AI, select its personality, its traits, its image and more. The process seems to be the same as the process already available in Messenger. One of the nice things that Meta provides when creating these AI bots is templates and suggestions such as the attitude of the bot or the instructions for the bot. This is the same as in Messenger and allows you to get started chatting with your custom bots faster. In terms of sharing, you have the option to make the bots private, share them with friends (at least in the case of Messenger and presumably WhatsApp), or share them publicly. If you make something specific for your needs then the private option would be best, while bots with mass appeal could be set to public. Creating bots in WhatsApp is straightforward once you have access to the AI Studio. During the creation process you’ll need to name your AI, define its personality, choose a tone, design an avatar (some will be made for you with Meta’s AI), and create a catchy tagline to attract users if you ever set it to public. Much of the information will be pre-filled based on the initial details you provide about the AI’s role and personality. Some ideas for bots that you can create include a motivational coach, a travel recommendation AI, or a daily planner. While setting up these AI bots is easy to do, users may find their actual benefits limited. Besides the nagging feeling that you’re socializing with a clever bit of code, Meta seems to truncate the answers of these bots so they don’t rattle on, but depending on what you want them to do, you may need them to give a lengthy response, but they won’t. What personalized AI chatbots could offer If you are looking for an AI that chats to you conversationally like real people do, then this could be the feature you’re looking for. The fact that you can personalize bots with specific traits is something you can’t do as easily in apps like ChatGPT and Gemini and the fact that they have an avatar makes them more connectable too. Two of the defining features of Meta’s AI implementation is the ability to create custom AIs with a unique personality and to share them publicly. If you are having difficulty thinking of what a bot could be instructed to do, you can easily find community bots and interact with those instead and may find they provide some value. While these bots could be interesting for some people, they do carry the same risks as other AIs and that is that they can hallucinate. There was also a case in the UK where a man had been encouraged by his Replika to break into Buckingham Palace with a crossbow to kill the then head of state. Similar issues to this could result from Meta’s AI chatbots in time. Potential pitfalls While the feature is pretty interesting there are some things to be aware of. Firstly, the feature is still in beta on WhatsApp so you may run into issues and things could change once it’s finally released. Meta also states that it uses your interactions to improve its AI services, for this reason it is essential not to share personal information as Meta could read it. While Meta does limit the creation of bots that go against its standards, the company also warns that bots can output harmful content, so this could be dangerous for impressionable people who end up acting on what an AI has said with negative outcomes. What to watch for next It’s not clear when these AI chatbots will be available in the stable channel but given that a wider rollout is underway among beta users perhaps we are not too far off. For most people, this is not going to be a must-have feature, just a nice to have. We’ve been using WhatsApp to chat with friends for years, so clearly the app is just fine without the inclusion of AI, but when it’s available, people may be able to get more value out of the app. When the feature launches for all users, bots should be discoverable in the same way they are on Messenger where they’re categorized by category allowing users to begin chats easily. It remains to be seen how users will interact with this feature in the long-run. Last year, we reported that Meta was looking to give bots profiles on its social networks and this was met by somebacklash in our comments section.
    • Microsoft confirms Windows Outlook breaks in many ways after major Calendar feature upgrade by Sayan Sen Microsoft has been trying to get more users onto New Outlook for Windows, and it is doing so not just by enforcing the newer app but also by making improvements along the way. In doing so, though, the company has caused the Classic Outlook app to bug out in the past. The classic app received a major Shared Calendar-related upgrade recently, with many " long-awaited improvements" as well as "small changes in form and function." As the name suggests, the Outlook Shared Calendar essentially allows multiple people to interact with and manage the calendar. With Shared Calendar improvements enabled, users will see the following changes: Instant sync and view of shared calendars Editing series end date does not reset the past Accepting meeting without having to send a response Last Modified By no longer shown in the meeting item Adding same calendar multiple times can't be done Duplicate calendars simultaneously selection Attachments addition not possible when responding to a meeting invitation Event drafts auto-save changes The "Download shared folders" setting is ignored Unfortunately, as with any major feature upgrade, there are bugs, and Microsoft has confirmed this is no different. The tech giant has shared official guidance for it so that users can work around the problems. According to the company, "Shared Calendar improvements are now enabled by default in the most recent versions of Outlook, in all update channels for Microsoft 365 Apps," and thus, the bugs are likely to affect many. Here are some of the bugs Microsoft is investigating, as well as their workarounds: Bug Workaround Meeting cancellation sent unexpectedly to some attendees in classic Outlook In a REST shared calendar, after adding or removing an attendee, or forwarding a meeting, a meeting cancellation may be sent unexpectedly to some attendees. Use the Outlook Web App or new Outlook when adding or removing an attendee or forwarding a meeting. Attendees do not get updates on attachment changes by Delegate When a delegate sends an update on a meeting that requires removing an attachment on an occurrence of a meeting series, the recipients may not get some or all of the attachment changes. In the delegate's Sync Issues folder, you'll see sync errors. Example: 17:23:26 Synchronizer Version 16.0.15313 17:23:26 Synchronizing Mailbox 'Delegate User' 17:23:26 Synchronizing local changes in folder 'Manager User' 17:23:27 Uploading to server 'https://outlook.office365.com/mapi/emsmdb/?xxxxxxxx-xx' 17:23:30 Error synchronizing folder 17:23:30 [0-320] There is no known workaround. It is recommended, whenever possible, to save attachments to SharePoint or to OneDrive and share with a link. After an attachment is deleted from an existing meeting, it may reappear after being deleted Please wait approximately one minute to give the sync time to complete. Additionally, it is advisable to save attachments to SharePoint or OneDrive whenever possible and share them using a link. A meeting created by a delegate with limited calendar access disappears and is unsent when a sensitivity label other than "Normal" is selected Three potential solutions to address this issue, each with their own implications for functionality: Manager can update delegate's permissions to allow viewing of private items. Delegate can change the sensitivity label of the meeting to "Normal". Delegate can disable Shared Calendar Improvements (not recommended). Aside from these, Microsoft has also fixed several other bugs, which you can find in the official support article here on the company's website.
    • I’ve just paid £290/$390 for a 4TB Samsung 990 Pro for my PS5 Pro so it’s not too far from the going rate. Microsoft should definitely copy Sony and let users buy their own SSD in their next consoles rather than this proprietary stuff. I paid £374/$505 for the 2TB Seagate card for my Series X a few years ago so it’s not exactly over priced. 4TB of NVMe storage ain’t cheap!
    • The EU regulations force companies to respect users privacy, choice and data. Something all tech companies have abused to the hilt and would continue to do so if it wasn’t for important legislation and laws the EU brought in, which have been adopted elsewhere around the world. The EU can be a nuisance, but they actually do more good than harm. Forcing Apple, Google, Microsoft etc to make changes hasn’t negatively impacted anyone apart from their financials as they aren’t free to pillage our data like they once were, unless they explicitly provide options to obtain consent.
    • Windows 10 Enterprise IoT LTSC will continue getting updates until January 2032. I would expect support from most programs to continue until then. Firefox still supports Windows 7 (until the end of August), which will be just over 16 years since release. Windows 10 will be of a very similar age in January 2032. I'm sure some things like games will move on earlier, but I imagine a Windows 10 machine will be safe and usable for a long time to come yet, despite the pressure and fearmongering from those who stand to gain from selling you a new PC.
  • Recent Achievements

    • Enthusiast
      Epaminombas went up a rank
      Enthusiast
    • Posting Machine
      Fiza Ali earned a badge
      Posting Machine
    • One Year In
      WaynesWorld earned a badge
      One Year In
    • First Post
      chriskinney317 earned a badge
      First Post
    • Week One Done
      Nullun earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      186
    2. 2
      snowy owl
      130
    3. 3
      ATLien_0
      129
    4. 4
      Xenon
      119
    5. 5
      +FloatingFatMan
      91
  • Tell a friend

    Love Neowin? Tell a friend!