Tree View hierarchical Dynamic C#

Asked

Viewed 809 times

2

I have the following situation, my select returns me 3 fields micro (son), descend(descend from the child) and macro(parent) micro and macros fields are integers and can be any number not following default (when I say default I refer to for example micro 2 does not necessarily have 1 as macro can be 3) and I need to fill a treeview with this information, I can make my query return the records in the orders in which have been added.

My table in the database has the following structure:

ID_HIERARQUIA NUMBER    
MICRO NUMBER    
DESCR VARCHAR2(300 BYTE)    
MACRO NUMBER    
POSICAO VARCHAR2(50 BYTE)

I used those insert's for testing:

INSERT INTO HIERARQUIA VALUES((SELECT NVL(MAX(ID_HIERARQUIA)+1,1) FROM 
HIERARQUIA),'08','EQUIPAMENTO 08','','01');    
INSERT INTO HIERARQUIA VALUES((SELECT NVL(MAX(ID_HIERARQUIA)+1,1) FROM HIERARQUIA),'04','EQUIPAMENTO 04','08','0101');    
INSERT INTO HIERARQUIA VALUES((SELECT NVL(MAX(ID_HIERARQUIA)+1,1) FROM HIERARQUIA),'02','EQUIPAMENTO 02','04','010101');    
INSERT INTO HIERARQUIA VALUES((SELECT NVL(MAX(ID_HIERARQUIA)+1,1) FROM HIERARQUIA),'03','EQUIPAMENTO 03','04','010102');    
INSERT INTO HIERARQUIA VALUES((SELECT NVL(MAX(ID_HIERARQUIA)+1,1) FROM HIERARQUIA),'05','EQUIPAMENTO 05','08','0102');    
INSERT INTO HIERARQUIA VALUES((SELECT NVL(MAX(ID_HIERARQUIA)+1,1) FROM HIERARQUIA),'06','EQUIPAMENTO 06','05','010201');    
INSERT INTO HIERARQUIA VALUES((SELECT NVL(MAX(ID_HIERARQUIA)+1,1) FROM HIERARQUIA),'07','EQUIPAMENTO 07','05','010202');    
INSERT INTO HIERARQUIA VALUES((SELECT NVL(MAX(ID_HIERARQUIA)+1,1) FROM HIERARQUIA),'01','EQUIPAMENTO 01','07','01020201');    
INSERT INTO HIERARQUIA VALUES((SELECT NVL(MAX(ID_HIERARQUIA)+1,1) FROM HIERARQUIA),'09','EQUIPAMENTO 09','07','01020202');

I tried the solution of that link

Where it feeds its list, I adapted it to receive the following query SELECT MICRO, DESCR, MACRO FROM HIERARQUIA ORDER BY POSICAO

But even though he feeds right he only creates the first Ode and doesn’t even add his children, if you can help me I am grateful.

1 answer

0


It’ll cost a bill...

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ExemploTreeView.aspx.cs"
  Inherits="WebApplication1tiraduvidas.ExemploTreeView" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <title></title>
</head>
<body>
  <form id="form1" runat="server">
  <div>
    <asp:TreeView ID="tvMenu" runat="server" ExpandDepth="0" CssClass="TView" PopulateNodesFromClient="false"
      ShowExpandCollapse="true" OnSelectedNodeChanged="tvMenu_SelectedNodeChanged" ImageSet="XPFileExplorer"
      SkipLinkText="" NodeStyle-CssClass="Node" SelectedNodeStyle-CssClass="NodeSel"
      HoverNodeStyle-CssClass="NodeHover">
      <RootNodeStyle ImageUrl="~/Images/folder.png" />
      <ParentNodeStyle ImageUrl="~/Images/folder.png" />
      <LeafNodeStyle ImageUrl="~/Images/folder.png" />
    </asp:TreeView>
  </div>
  </form>
</body>
</html>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

namespace WebApplication1tiraduvidas
{
    public partial class ExemploTreeView : System.Web.UI.Page
    {
        public string myConnString
        {
            get
            {
                return "Server=.\\SQLEXPRESS;Database=Teste;User ID=sa;Password=teste";
            }
        }

        private DataTable m_HIERARQUIA = null;
        private DataTable HIERARQUIA_
        {
            get
            {
                SqlConnection conn = new SqlConnection();
                conn.ConnectionString = myConnString;
                try
                {
                    SqlCommand cmd = new SqlCommand();
                    cmd.Connection = conn;
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = "select micro, macro, DESCR from HIERARQUIA order by POSICAO";

                    SqlDataAdapter da = new SqlDataAdapter();
                    DataTable dt = new DataTable();

                    da.SelectCommand = cmd;
                    conn.Open();
                    da.Fill(dt);
                    conn.Close();
                    m_HIERARQUIA = dt;
                }
                catch (Exception Exc)
                {
                }
                return m_HIERARQUIA;

            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            DataRow[] parents = HIERARQUIA_.Select("[macro] is null");

            Int32 IdPai = 0;

            foreach (DataRow dr in parents)
            {
                IdPai = (Int32)dr["micro"];
            }

            PopulateNodes(parents, tvMenu.Nodes, IdPai);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="fluxos"></param>
        /// <param name="node"></param>
        /// <param name="micro_"></param>
        private void PopulateNodes(DataRow[] fluxos, TreeNodeCollection node, Int32 micro_)
        {
            foreach (DataRow dr in fluxos)
            {
                TreeNode Node = new TreeNode();
                Node.Text = dr["DESCR"].ToString();
                Node.Value = dr["micro"].ToString();
                Node.ImageUrl = "~/Images/folder.png";
                node.Add(Node);

                DataRow[] Filhos = HIERARQUIA_
                    .Select("[macro] =" + dr["micro"]);

                if (Filhos.Length > 0)                       // Recursivo !!
                    PopulateNodes(Filhos, Node.ChildNodes, micro_);

                // É o selecionado ?
                if (Convert.ToInt32(dr["micro"]) == micro_)
                {
                    Node.Selected = true;       // Seleciona e mostra eventuais filhos
                    Node.Expand();

                    TreeNode Pai = Node.Parent;      // Expande os pais
                    while (Pai != null)
                    {
                        Pai.Expand();
                        Pai = Pai.Parent;
                    }
                }
            }
        }

        protected void tvMenu_SelectedNodeChanged(object sender, EventArgs e)
        {
            DataRow[] parents = HIERARQUIA_.Select("[macro] is null");
            Int32 IdNode = Convert.ToInt32(tvMenu.SelectedNode.Value);
            tvMenu.Nodes.Clear();
            PopulateNodes(parents, tvMenu.Nodes, IdNode);
        }
    }
}

Bench

CREATE TABLE [dbo].[HIERARQUIA](
    [ID_HIERARQUIA] [int] IDENTITY(1,1) NOT NULL,
    [MICRO] [int] NOT NULL,
    [DESCR] [varchar](250) NOT NULL,
    [MACRO] [int] NULL,
    [POSICAO] [varchar](250) NOT NULL,
 CONSTRAINT [PK_HIERARQUIA] PRIMARY KEY CLUSTERED 
(
    [ID_HIERARQUIA] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

INSERT INTO HIERARQUIA  ([MICRO],[DESCR],[MACRO],[POSICAO]) VALUES
 (1,'EQUIPAMENTO 08', null,'01')
,(2,'EQUIPAMENTO 04', 1,'0101')
,(3,'EQUIPAMENTO 02', 1,'010101')
,(4,'EQUIPAMENTO 03', 1,'010102')
,(5,'EQUIPAMENTO 05', 2,'0102')
,(6,'EQUIPAMENTO 06', 2,'010201')
,(7,'EQUIPAMENTO 07', 2,'010202')
,(8,'EQUIPAMENTO 01', 5,'01020201')
,(9,'EQUIPAMENTO 09', 5,'01020202')

inserir a descrição da imagem aqui

  • I will try to adapt here, I forgot to inform that it was Windows Forms.. thank you !!!

  • The idea is the same only if you look at the Populatenodes method, that you don’t need to change.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.