|
<< Click to Display Table of Contents >> TreeView - buscando grupos de base recursivamente |
![]() ![]()
|
Tela

Banco de dados (mySql)
CREATE TABLE tb_grupo (
id int(11) NOT NULL AUTO_INCREMENT,
nome varchar(20) NOT NULL,
id_pai int(11) DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=latin1;
Dados
INSERT INTO tb_grupo (id, nome, id_pai) VALUES
(1,'Eletronicos',NULL),
(2,'Livros',NULL),
(3,'Games',NULL),
(4,'TV',1),
(5,'Som',1),
(6,'LG 5500',4),
(7,'Samsung S20',4),
(8,'Ficção',2),
(9,'Não-Ficção',2),
(10,'Guia do Mochileiro',8),
(11,'Wii',3),
(12,'PS3',3),
(13,'Acessórios',11),
(14,'Jogos',11),
(15,'Mario Galaxy 2',14),
(16,'Zelda',14),
(17,'Volante',13),
(18,'C# como programar',9),
(19,'Use a cabeça burro',9);
Default.aspx
<div>
<asp:TreeView ID="TreeView1" runat="server" OnSelectedNodeChanged="TreeView1_SelectedNodeChanged" ShowLines="True"></asp:TreeView>
</div>
Default.aspx.cs
using System;
using System.Data;
using System.Web.UI.WebControls;
using MySql.Data.MySqlClient;
public partial class _Default : System.Web.UI.Page
{
private MySqlConnection conexao;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
PopularTreeView();
}
}
public void PopularTreeView()
{
using (conexao = new MySqlConnection("server=localhost;User Id=root;Persist Security Info=True;database=teste;Password=123456"))
{
conexao.Open();
PreencheFilhos(null);
}
}
public void PreencheFilhos(TreeNode noPai)
{
string sql = (noPai == null ? "is null" : "=@id_pai");
// monta o sql
MySqlCommand cmd = new MySqlCommand("select id, nome, id_pai from tb_grupo where id_pai " + sql, conexao);
// só tem parâmetro se não for "raiz"
if (noPai != null)
cmd.Parameters.AddWithValue("@id_pai", noPai.Value);
// monta um adapter para preencher um datatable (não usei um executeReader,
// porque não pode ter 2 execute reader aberto no mesma conexao!)
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataTable tabela = new DataTable();
da.Fill(tabela);
// pra cada linha...
foreach (DataRow row in tabela.Rows)
{
// cria um nó
TreeNode node = new TreeNode(row["nome"].ToString(), row["id"].ToString());
// se não for do raiz coloca como filho
if (noPai != null)
noPai.ChildNodes.Add(node);
else
TreeView1.Nodes.Add(node);
// recursiva!
PreencheFilhos(node);
}
}
protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e)
{
Response.Write("Id do objeto selecionado: " + TreeView1.SelectedValue.ToString() + "<br>");
}
}