logo
down
shadow

C# WPF: Create TreeView from text file


C# WPF: Create TreeView from text file

By : Muhammad
Date : November 28 2020, 11:01 PM
will be helpful for those in need I create my TreeViewItems with the class Node . In the example nodes are specified in source code. But how do I do it if the nodes are to be imported from a text file with content like this: , input example
code :
Root|A
Root|B|C
Root|B|D
Root|E
 public MainWindowVM()
{
    private ObservableCollection<Node> mRootNodes;
    public IEnumerable<Node> RootNodes { get { return mRootNodes; } }

    string[] lines = null;
    try
    {
        lines = System.IO.File.ReadAllLines(MainWindow.TextFilePath , System.Text.Encoding.Default);
    }
    catch (IOException ex)
    {
        MessageBox.Show(ex.Message);
        Environment.Exit(0);
    }
    if (lines == null || lines.Length == 0)
    {
        MessageBox.Show("Text file has no content!");
        Environment.Exit(0);
    }
    Dictionary<string, Node> nodeCache = new Dictionary<string, Node>();
    // processing each line
    foreach (var line in lines)
    {                
        Node parentNode = null;
        string key = null;
        // in each line there are one or more node names, separated by | char
        foreach (string childNodeName in line.Split('|'))
        {
            Node childNode;
            // names are not unique, we need a composite key (full node path)
            key += "|" + childNodeName;
            // each node has unique key
            // if key doesn't exists in cache, we need to create new child node
            if (false == nodeCache.TryGetValue(key, out childNode))
            {
                childNode = new Node { Name = childNodeName };
                nodeCache.Add(key, childNode);

                if (parentNode != null)
                    // each node (exept root) has a parent
                    // we need to add a child node to parent ChildRen collection
                    parentNode.Children.Add(childNode);
                else 
                    // root nodes are stored in a separate collection
                    mRootNodes.Add(childNode);
            }

            // saving current node for next iteration
            parentNode = childNode;
        }
    }
}


Share : facebook icon twitter icon
avoid treeview collapse on click of treeview text in jquery

avoid treeview collapse on click of treeview text in jquery


By : Silvestre Gil
Date : March 29 2020, 07:55 AM
will help you You'll need to update the treeview javascript code itself. For Treeview 1.4, comment out the following lines (66-68):
code :
this.filter(":has(>ul):not(:has(>a))").find(">span").click(function(event) {
    toggler.apply($(this).next());
}).add( $("a", this) ).hoverClass();
if (settings.expandMode != 'simple'){
    this.filter(":has(>ul):not(:has(>a))").find(">span").click(function(event) {
        toggler.apply($(this).next());
    }).add( $("a", this) ).hoverClass();
}
$("#tree").treeview({
    animated: "fast",
    persist: "cookie",
    collapsed: true,
    control: "#treecontrol",
    expandMode: "simple" // custom - only toggles per the +/- icon      
})
How to write the contents of a treeview to a text file

How to write the contents of a treeview to a text file


By : Dhaval CHARADVA
Date : March 29 2020, 07:55 AM
I wish did fix the issue. There's a number of ways that you could accomplish this but I believe the best way would be to save the treeview nodes as binary data to a flat file and read it back when you need it.
Here is a simple example. You can create a new vb.net winforms project and just copy/paste this code over the code for Form1 and click 'Run':
code :
Public Class Form1
    Dim tv As New TreeView
    Dim cmdSave As New Button
    Dim cmdClear As New Button
    Dim cmdLoad As New Button

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        ' Setup control positions and values

        tv.Location = New Point(0, 0)
        tv.Size = New Size(Me.Width, Me.ClientSize.Height - cmdSave.Height)
        cmdSave.Location = New Point(0, Me.ClientSize.Height - cmdSave.Height)
        cmdSave.Text = "Save"
        AddHandler cmdSave.Click, AddressOf cmdSave_Click
        cmdClear.Location = New Point(cmdSave.Left + cmdSave.Width, Me.ClientSize.Height - cmdClear.Height)
        cmdClear.Text = "Clear"
        AddHandler cmdClear.Click, AddressOf cmdClear_Click
        cmdLoad.Location = New Point(cmdClear.Left + cmdClear.Width, Me.ClientSize.Height - cmdLoad.Height)
        cmdLoad.Text = "Load"
        AddHandler cmdLoad.Click, AddressOf cmdLoad_Click

        ' Build the treeview

        tv.Nodes.Add("Node 1")
        tv.Nodes(tv.Nodes.Count - 1).Nodes.Add("Node 1 - Child 1")
        tv.Nodes(tv.Nodes.Count - 1).Nodes.Add("Node 1 - Child 2")
        tv.Nodes(tv.Nodes.Count - 1).Nodes.Add("Node 1 - Child 3")
        tv.Nodes.Add("Node 2")
        tv.Nodes(tv.Nodes.Count - 1).Nodes.Add("Node 2 - Child 1")
        tv.Nodes(tv.Nodes.Count - 1).Nodes.Add("Node 2 - Child 2")
        tv.Nodes(tv.Nodes.Count - 1).Nodes.Add("Node 2 - Child 3")

        tv.ExpandAll()

        ' Add controls to the form

        Me.Controls.Add(tv)
        Me.Controls.Add(cmdSave)
        Me.Controls.Add(cmdClear)
        Me.Controls.Add(cmdLoad)
    End Sub

    Private Sub cmdSave_Click(sender As Object, e As EventArgs)
        Try
            Dim dlg As New SaveFileDialog

            dlg.DefaultExt = "sav"
            dlg.Filter = "sav files|*.sav"
            dlg.OverwritePrompt = True

            If dlg.ShowDialog = Windows.Forms.DialogResult.OK Then
                ' Save the treeview nodes to file

                Dim oTreeList As New List(Of clsTreeFile)

                For Each oNode As TreeNode In tv.Nodes
                    Dim oTree As New clsTreeFile

                    oTree.oTreeNode = oNode
                    oTreeList.Add(oTree)
                Next

                Using oFileStream As IO.FileStream = IO.File.Open(dlg.FileName, IO.FileMode.Create)
                    Dim oBinaryFormatter As New Runtime.Serialization.Formatters.Binary.BinaryFormatter
                    oBinaryFormatter.Serialize(oFileStream, oTreeList)
                End Using

                MessageBox.Show("Treeview saved successfully.", "File saved", MessageBoxButtons.OK, MessageBoxIcon.Information)
            End If
        Catch ex As Exception
            MessageBox.Show("An error occurred while saving:" & vbCrLf & ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        End Try
    End Sub

    Private Sub cmdClear_Click(sender As Object, e As EventArgs)
        tv.Nodes.Clear()
    End Sub

    Private Sub cmdLoad_Click(sender As Object, e As EventArgs)
        Dim dlg As New OpenFileDialog

        Try
            dlg.DefaultExt = "sav"
            dlg.Filter = "SAV files|*.sav"

            If dlg.ShowDialog = Windows.Forms.DialogResult.OK Then
                ' Open saved file and read the binary data back to the treeview

                tv.Nodes.Clear()

                Dim oTreeList As New List(Of clsTreeFile)

                Using oFileStream As IO.FileStream = IO.File.Open(dlg.FileName, IO.FileMode.Open)
                    Dim oBinaryFormatter As New Runtime.Serialization.Formatters.Binary.BinaryFormatter
                    oTreeList = CType(oBinaryFormatter.Deserialize(oFileStream), List(Of clsTreeFile))
                End Using

                For Each oNode As clsTreeFile In oTreeList
                    tv.Nodes.Add(oNode.oTreeNode)
                Next

                tv.ExpandAll()
            End If
        Catch ex As Exception
            MessageBox.Show("The " & System.IO.Path.GetFileName(dlg.FileName) & " file cannot be opened." & vbCrLf & vbCrLf & ex.Message, "Error opening file", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub
End Class

<Serializable()> _
Public Class clsTreeFile
    Public oTreeNode As TreeNode
End Class
Create TreeView from existing TreeView's checked checkboxes

Create TreeView from existing TreeView's checked checkboxes


By : John Glenn
Date : March 29 2020, 07:55 AM
seems to work fine Ended up using a Dynatree instead of using treeview.
with support from this: How can I read parent nodes with partly selected child nodes
code :
    $(function () {
        $("#tree").dynatree({
            checkbox: true,
            selectMode: 3,
            onSelect: function (select, node) {
                var selKeys = $.map(node.tree.getSelectedNodes(), function (node) {
                    return node.data.key;
                });
                var partsel = new Array();
                $(".dynatree-partsel:not(.dynatree-selected)").each(function () {
                    var node = $.ui.dynatree.getNode(this);
                    partsel.push(node.data.key);
                });

                selKeys = selKeys.concat(partsel);                 
            },
            onClick: function (node, event) {

                if (node.getEventTargetType(event) == "title")
                    node.toggleSelect();
            },
            onDblClick: function (node, event) {
                node.toggleSelect();
            },
            onKeydown: function (node, event) {
                if (event.which == 32) {
                    node.toggleSelect();
                    return false;
                }
            }           
        });
    });
Create a Gtk.TreeView from a flat file list GTK C#

Create a Gtk.TreeView from a flat file list GTK C#


By : Sunil Pandya
Date : March 29 2020, 07:55 AM
may help you . TreeView is a powerful widget, in my opinion a too powerful mixing. I wrote a GtkUtil module that contains the GtkTableTextView class, which makes it easier to user the TreeView.
With this class, you will be able to create the table as follows:
code :
var tvTable = new Gtk.TreeView();
this.Add( tvTable );

var Headers = new string[] { "#", "Path" };
var ttTable = new GtkUtil.TableTextView( this.tvTable, Headers.Count, Headers.Count );
ttTable.Headers = Headers;

foreach(string path in paths) {
    ttTable.AppendRow();
    ttTable.Set( i, 1, path );
}

this.ShowAll();
var tree = new Gtk.TreeView ();
this.Add( tree );

// Create a column for the file path
Gtk.TreeViewColumn pathColumn = new Gtk.TreeViewColumn ();
pathColumn.Title = "Path";
tree.appendColumn( pathColumn );

// Create an appropriate model
var pathListStore = new Gtk.ListStore( typeof( string ) );
tree.Model = pathListStore;

// Add the data
foreach(string path in paths) {
    tree.AppendValues( path );
}

this.ShowAll();
How to create treeview from XML file using WPF?

How to create treeview from XML file using WPF?


By : Walter
Date : March 29 2020, 07:55 AM
like below fixes the issue Here is a way to do it programmatically. This is based on this website's solution
shadow
Privacy Policy - Terms - Contact Us © soohba.com