How to set data from DataTable to TreeView

Mansour_Dalir 1,956 Reputation points
2023-07-01T13:44:36.4433333+00:00

If possible, first convert it to a multidimensional array through 'LINQ 'and then set it to TreeView L=LEVEL .Thank you with all due respect

treeView

   Dim MyDataTable As New DataTable
        MyDataTable.Columns.Add("A")
        MyDataTable.Columns.Add("B")
        MyDataTable.Columns.Add("C")
        MyDataTable.Rows.Add({"a", "aL2_1", "aL3_1"})
        MyDataTable.Rows.Add({"b", "bL2_1", "bL3_2"})
        MyDataTable.Rows.Add({"a", "aL2_1", "aL3_2"})
        MyDataTable.Rows.Add({"a", "aL2_2", "aL3_1"})
        MyDataTable.Rows.Add({"b", "bL2_1", "bL3_1"})
        MyDataTable.Rows.Add({"c", "cL2_1", "cL3_1"})
VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,740 questions
0 comments No comments
{count} votes

Accepted answer
  1. Jiachen Li-MSFT 32,376 Reputation points Microsoft Vendor
    2023-07-03T01:35:45.6733333+00:00

    Hi @Mansour_Dalir ,

    You can refer to the following code.

            Dim array = (From row In MyDataTable.AsEnumerable()
                         Select row.ItemArray).ToArray()
    
            For Each item In array
                Dim parentNode As TreeNode = Nothing
                For i = 0 To item.Length - 1
                    Dim value = item(i).ToString()
                    Dim node As TreeNode = Nothing
    
                    If parentNode IsNot Nothing Then
                        node = parentNode.Nodes.Cast(Of TreeNode)() _
                            .FirstOrDefault(Function(n) n.Text = value)
                    Else
                        node = TreeView1.Nodes.Cast(Of TreeNode)() _
                            .FirstOrDefault(Function(n) n.Text = value)
                    End If
    
                    If node Is Nothing Then
                        node = New TreeNode(value)
                        If parentNode IsNot Nothing Then
                            parentNode.Nodes.Add(node)
                        Else
                            TreeView1.Nodes.Add(node)
                        End If
                    End If
    
                    parentNode = node
                Next
            Next
    

    Best Regards.

    Jiachen Li


    If the answer is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.