Usuário com melhor resposta
Preencher TreeView

Pergunta
-
Respostas
-
Rafael,
Na verdade a maneira como você está fazendo não está correta, mas vou ajudá-lo. Faça o seguinte:
1 - Comente a linha abaixo.
'Dim lista = ListarPla()
2 - Comente a linha abaixo:
'' ordena lista pelo nível
'lista.Sort(Function(x, y) x.Nivel.CompareTo(y.Nivel))
e substitua pelo código abaixo:
' ordena lista pelo nível e pela conta
Dim l = From q In lista _
Order By q.Nivel, q.PlaConta _
Select q
lista = l.ToList()
Att.
Ari C. Raimundo- Marcado como Resposta rafaeldorazio quarta-feira, 21 de outubro de 2009 01:35
-
Rafael,
Segue o código em VB.NET.
Public Class FormTeste
Public Class PlaInfo
Public PlaConta As String
Public PlaDescr As String
Public PlaPai As PlaInfo
Public Nivel As Integer
End Class
Private Function ListarPla() As List(Of PlaInfo)
Dim lista As New List(Of PlaInfo)
lista.Add(New PlaInfo With {.PlaConta = "1", .PlaDescr = "RECEITAS", .Nivel = 1, .PlaPai = Nothing})
lista.Add(New PlaInfo With {.PlaConta = "1.01", .PlaDescr = "RECEITAS OPERACIONAIS", .Nivel = 2, .PlaPai = Nothing})
lista.Add(New PlaInfo With {.PlaConta = "1.01.01", .PlaDescr = "CLIENTES", .Nivel = 3, .PlaPai = Nothing})
lista.Add(New PlaInfo With {.PlaConta = "1.01.02", .PlaDescr = "CLIENTES DUVIDOSOS", .Nivel = 3, .PlaPai = Nothing})
lista.Add(New PlaInfo With {.PlaConta = "1.02", .PlaDescr = "OUTRAS RECEITAS", .Nivel = 2, .PlaPai = Nothing})
lista.Add(New PlaInfo With {.PlaConta = "1.02.01", .PlaDescr = "RECEITAS ESPECIAIS", .Nivel = 3, .PlaPai = Nothing})
lista.Add(New PlaInfo With {.PlaConta = "2", .PlaDescr = "DESPESAS", .Nivel = 1, .PlaPai = Nothing})
lista.Add(New PlaInfo With {.PlaConta = "2.01", .PlaDescr = "DESPESAS FIXAS", .Nivel = 2, .PlaPai = Nothing})
lista.Add(New PlaInfo With {.PlaConta = "2.01.01", .PlaDescr = "IMPOSTOS", .Nivel = 3, .PlaPai = Nothing})
lista.Add(New PlaInfo With {.PlaConta = "2.01.01.01", .PlaDescr = "IPI", .Nivel = 4, .PlaPai = Nothing})
lista.Add(New PlaInfo With {.PlaConta = "2.02", .PlaDescr = "DESPESAS EXTRAS", .Nivel = 2, .PlaPai = Nothing})
ListarPla = lista
End Function
Private Sub btnListar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnListar.Click
' lista itens
Dim lista = ListarPla()
' loop na lista para buscar o pai
For Each plaInfo In lista
' chave do pai
Dim chavePai As String = ""
If plaInfo.PlaConta.Contains(".") Then
chavePai = plaInfo.PlaConta.Substring(0, plaInfo.PlaConta.LastIndexOf("."))
End If
' busca pelo pai
Dim pai = (From plaPai In lista _
Where plaPai.PlaConta = chavePai _
Select plaPai).SingleOrDefault()
' verifica se o pai foi encontrado
If pai IsNot Nothing Then
plaInfo.PlaPai = pai
End If
Next plaInfo
' inicializa edição da treeView
Me.treeView.BeginUpdate()
' limpa treeView
Me.treeView.Nodes.Clear()
' ordena lista pelo nível
lista.Sort(Function(x, y) x.Nivel.CompareTo(y.Nivel))
' adiciona nós
For Each plaInfo In lista
if (plaInfo.PlaPai Is Nothing) then
Me.treeView.Nodes.Add(plaInfo.PlaConta, plaInfo.PlaDescr)
Else
Dim treeNodePai = Me.treeView.Nodes.Find(plaInfo.PlaPai.PlaConta, True)
If (treeNodePai IsNot Nothing) Then
treeNodePai(0).Nodes.Add(plaInfo.PlaConta, plaInfo.PlaDescr)
End If
End If
Next plaInfo
' finaliza edição da treeView
Me.treeView.EndUpdate()
End Sub
End Class
Att.
Ari C. Raimundo- Sugerido como Resposta Ari C. Raimundo terça-feira, 13 de outubro de 2009 20:19
- Marcado como Resposta Fernanda SimõesModerator quarta-feira, 14 de outubro de 2009 11:48
Todas as Respostas
-
-
Então, os dados vão vir de 1 ( uma) tabela do banco de dados.
Encontrei muitos exemplo no qual uma coluna do banco de dados servia como filho, mas isso não vai funcionar aqui porque na coluna do banco de dados ela pode ser filho ou pai.
Na Coluna do banco nós estamos usando assim: pla_conta_pai, esta coluna ela identifica o pai do registro !
Teria algum exemplo ?
Rafael Fernandes D Orazio -
Sem sabe a hierarquia só vejo solução fazendo uma rotina que faça uma pesquisa nos nós já adicionados. Tipo, agora você deseja incluir um nó filho do nó Conta01, então você tem que procurar o nó Conta01 e abaixo dela adicionar esse nó filho, ou seja, não seria nada sequencial.
Visite a Zona .NET: http://zonadotnet.wordpress.com | http://lblima.blogspot.com
Ari C. Raimundo
pla_conta(pk) pla_descr pla_nivel
1 RECEITAS 1
1.01 DECEITAS OPERACIONAIS 2
1.01.01 CLIENTES 3
1.01.02 CLIENTES DUVIDOSOS 3
1.02 OUTRAS RECEITAS 2
1.02.01 RECEITAS ESPECIAIS 3
2 DESPESAS 1
2.01 DESPESAS FIXAS 2
2.01.01 IMPOSTOS 3
2.01.01.01 IPI 4
2.02 DESPESAS EXTRAS 2
Rafael Fernandes D OrazioRafael,
O código abaixo pode ser colocado em um form qualquer. O método ListarPla deve ser substituído pelo método que você utiliza para listar os seus registros (fiz a inicialização direto no código). O código está em C#, favor transformá-lo para VB.NET.
class PlaInfo
{
public string PlaConta { get; set; }
public string PlaDescr { get; set; }
public PlaInfo PlaPai { get; set; }
public int Nivel { get; set; }
}
static List<PlaInfo> ListarPla()
{
List<PlaInfo> lista = new List<PlaInfo>() {
new PlaInfo() { PlaConta = "1", PlaDescr="RECEITAS", Nivel = 1, PlaPai = null },
new PlaInfo() { PlaConta = "1.01", PlaDescr="RECEITAS OPERACIONAIS", Nivel = 2, PlaPai = null },
new PlaInfo() { PlaConta = "1.01.01", PlaDescr="CLIENTES", Nivel = 3, PlaPai = null },
new PlaInfo() { PlaConta = "1.01.02", PlaDescr="CLIENTES DUVIDOSOS", Nivel = 3, PlaPai = null },
new PlaInfo() { PlaConta = "1.02", PlaDescr="OUTRAS RECEITAS", Nivel = 2, PlaPai = null },
new PlaInfo() { PlaConta = "1.02.01", PlaDescr="RECEITAS ESPECIAIS", Nivel = 3, PlaPai = null },
new PlaInfo() { PlaConta = "2", PlaDescr="DESPESAS", Nivel = 1, PlaPai = null },
new PlaInfo() { PlaConta = "2.01", PlaDescr="DESPESAS FIXAS", Nivel = 2, PlaPai = null },
new PlaInfo() { PlaConta = "2.01.01", PlaDescr="IMPOSTOS", Nivel = 3, PlaPai = null },
new PlaInfo() { PlaConta = "2.01.01.01", PlaDescr="IPI", Nivel = 4, PlaPai = null },
new PlaInfo() { PlaConta = "2.02", PlaDescr="DESPESAS EXTRAS", Nivel = 2, PlaPai = null }
};
return lista;
}
private void btnListar_Click(object sender, EventArgs e)
{
// lista itens
List<PlaInfo> lista = ListarPla();
// loop na lista para buscar o pai
lista.ForEach(plaInfo =>
{
// chave do pai
string chavePai = plaInfo.PlaConta.Contains(".") ?
plaInfo.PlaConta.Substring(0, plaInfo.PlaConta.LastIndexOf(".")) : "";
// busca pelo pai
var pai = (from plaPai in lista
where plaPai.PlaConta == chavePai
select plaPai).SingleOrDefault();
// verifica se o pai foi encontrado
if (pai != null)
plaInfo.PlaPai = pai;
});
// inicializa edição da treeView
this.treeView.BeginUpdate();
// limpa treeView
this.treeView.Nodes.Clear();
// ordena lista pelo nível
lista.Sort(delegate(PlaInfo x, PlaInfo y){
return x.Nivel.CompareTo(y.Nivel);
});
// adiciona nós
lista.ForEach(plaInfo => {
if (plaInfo.PlaPai == null)
this.treeView.Nodes.Add(plaInfo.PlaConta, plaInfo.PlaDescr);
else
{
TreeNode[] treeNodePai = this.treeView.Nodes.Find(plaInfo.PlaPai.PlaConta, true);
if (treeNodePai != null)
treeNodePai[0].Nodes.Add(plaInfo.PlaConta, plaInfo.PlaDescr);
}
});
// finaliza edição da treeView
this.treeView.EndUpdate();
}
Espero ter ajudado.
Att.
Ari C. RaimundoAri me desculpe, mas eu tentei aqui, e nao entendi muito bem como eu devo utilizar .
Nolista.ForEach(
Function(Pla_Conta) Do
----> deu erro de Expression Expected
2º erro
lista.Sort(
Function(x As Pla_Conta, y As PlaInfo) x.Nivel.CompareTo(y.Nivel))
Public Sub Sort(comparison As System.Comparison(Of Pla_Conta))
'Public Sub Sort(comparer As System.Collections.Generic.IComparer(Of Pla_Conta))': Lambda expression cannot be converted to 'System.Collections.Generic.IComparer(Of Simple.Pla_Conta)' because 'System.Collections.Generic.IComparer(Of Simple.Pla_Conta)' is not a delegate type.
3º erro
Dim pai = (From plaPai In lista _
Where plaPai.PlaConta = chavePai _
Select plaPai).SingleOrDefault()
Error 2 Expression of type 'System.Collections.Generic.List(Of Simple.Pla_Conta)' is not queryable. Make sure you are not missing an assembly reference and/or namespace import for the LINQ provider.
Eu converti para vb.net , mas deu nisso :(.Error 3 Overload resolution failed because no accessible 'Sort' can be called with these arguments:
Public Sub Sort(comparison As System.Comparison(Of Pla_Conta))
'Public Sub Sort(comparer As System.Collections.Generic.IComparer(Of Pla_Conta))': Lambda expression cannot be converted to 'System.Collections.Generic.IComparer(Of Simple.Pla_Conta)' because 'System.Collections.Generic.IComparer(Of Simple.Pla_Conta)' is not a delegate type.
3º erro
Dim pai = (From plaPai In lista _
Where plaPai.PlaConta = chavePai _
Select plaPai).SingleOrDefault()
Error 2 Expression of type 'System.Collections.Generic.List(Of Simple.Pla_Conta)' is not queryable. Make sure you are not missing an assembly reference and/or namespace import for the LINQ provider.
Eu converti para vb.net , mas deu nisso :(.
Rafael Fernandes D OrazioRafael,
Segue o código em VB.NET.
Public Class FormTeste
Public Class PlaInfo
Public PlaConta As String
Public PlaDescr As String
Public PlaPai As PlaInfo
Public Nivel As Integer
End Class
Private Function ListarPla() As List(Of PlaInfo)
Dim lista As New List(Of PlaInfo)
lista.Add(New PlaInfo With {.PlaConta = "1", .PlaDescr = "RECEITAS", .Nivel = 1, .PlaPai = Nothing})
lista.Add(New PlaInfo With {.PlaConta = "1.01", .PlaDescr = "RECEITAS OPERACIONAIS", .Nivel = 2, .PlaPai = Nothing})
lista.Add(New PlaInfo With {.PlaConta = "1.01.01", .PlaDescr = "CLIENTES", .Nivel = 3, .PlaPai = Nothing})
lista.Add(New PlaInfo With {.PlaConta = "1.01.02", .PlaDescr = "CLIENTES DUVIDOSOS", .Nivel = 3, .PlaPai = Nothing})
lista.Add(New PlaInfo With {.PlaConta = "1.02", .PlaDescr = "OUTRAS RECEITAS", .Nivel = 2, .PlaPai = Nothing})
lista.Add(New PlaInfo With {.PlaConta = "1.02.01", .PlaDescr = "RECEITAS ESPECIAIS", .Nivel = 3, .PlaPai = Nothing})
lista.Add(New PlaInfo With {.PlaConta = "2", .PlaDescr = "DESPESAS", .Nivel = 1, .PlaPai = Nothing})
lista.Add(New PlaInfo With {.PlaConta = "2.01", .PlaDescr = "DESPESAS FIXAS", .Nivel = 2, .PlaPai = Nothing})
lista.Add(New PlaInfo With {.PlaConta = "2.01.01", .PlaDescr = "IMPOSTOS", .Nivel = 3, .PlaPai = Nothing})
lista.Add(New PlaInfo With {.PlaConta = "2.01.01.01", .PlaDescr = "IPI", .Nivel = 4, .PlaPai = Nothing})
lista.Add(New PlaInfo With {.PlaConta = "2.02", .PlaDescr = "DESPESAS EXTRAS", .Nivel = 2, .PlaPai = Nothing})
ListarPla = lista
End Function
Private Sub btnListar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnListar.Click
' lista itens
Dim lista = ListarPla()
' loop na lista para buscar o pai
For Each plaInfo In lista
' chave do pai
Dim chavePai As String = ""
If plaInfo.PlaConta.Contains(".") Then
chavePai = plaInfo.PlaConta.Substring(0, plaInfo.PlaConta.LastIndexOf("."))
End If
' busca pelo pai
Dim pai = (From plaPai In lista _
Where plaPai.PlaConta = chavePai _
Select plaPai).SingleOrDefault()
' verifica se o pai foi encontrado
If pai IsNot Nothing Then
plaInfo.PlaPai = pai
End If
Next plaInfo
' inicializa edição da treeView
Me.treeView.BeginUpdate()
' limpa treeView
Me.treeView.Nodes.Clear()
' ordena lista pelo nível
lista.Sort(Function(x, y) x.Nivel.CompareTo(y.Nivel))
' adiciona nós
For Each plaInfo In lista
if (plaInfo.PlaPai Is Nothing) then
Me.treeView.Nodes.Add(plaInfo.PlaConta, plaInfo.PlaDescr)
Else
Dim treeNodePai = Me.treeView.Nodes.Find(plaInfo.PlaPai.PlaConta, True)
If (treeNodePai IsNot Nothing) Then
treeNodePai(0).Nodes.Add(plaInfo.PlaConta, plaInfo.PlaDescr)
End If
End If
Next plaInfo
' finaliza edição da treeView
Me.treeView.EndUpdate()
End Sub
End Class
Att.
Ari C. Raimundo- Sugerido como Resposta Ari C. Raimundo terça-feira, 13 de outubro de 2009 20:19
- Marcado como Resposta Fernanda SimõesModerator quarta-feira, 14 de outubro de 2009 11:48
Dim
pai = (From plaPai In lista Where plaPai.PlaConta = chavePai Select plaPai).SingleOrDefault()
no lista esta dando o seguinte erro :
Error 9 Expression of type 'System.Collections.Generic.List(Of Simple.frmfin008.PlaInfo)' is not queryable. Make sure you are not missing an assembly reference and/or namespace import for the LINQ provider.
Esses são os Imports que eu estou usando
Imports
System
Imports Microsoft.VisualBasic
Imports System.Collections
Imports System.Collections.Generic
Rafael Fernandes D OrazioRafael,
O código que lhe passei compilou normalmente no VS2008 SP1.
Acho que falta referenciar alguns assemblies. Segue link de ajuda:
Expression of type <type> is not queryable
http://msdn.microsoft.com/en-us/library/bb763092.aspx
Att.
Ari C. RaimundoTenho uma duvida, estou querendo enserir um novo nó, mas em tempo de execução .
Public Sub AdicionaNó(ByVal TreeView As TreeView, ByVal Descr As String, ByVal ID As String) Dim classPlaInfo As New PlaInfo() classPlaInfo.PlaConta = ID classPlaInfo.PlaDescr = Descr classPlaInfo.PlaPai = Nothing CarregarTreeView(TreeView) End Sub
O carregarTreeview é oPrivate Sub btnListar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnListar.Click
do codigo que o Ari postou ! E quando entra nele ele nao adiciona o nó, pq ?
Rafael Fernandes D OrazioRafael,
Sim, a variável lista que é declarada dentro do evento btnListar_Click poderia ser declarada como atributo do formulário, assim depois que você criasse uma nova instância da classe PlaInfo você poderia adicioná-la à lista.
Segue um exemplo abaixo:
Public Class FormTeste
Public Class PlaInfo
Public PlaConta As String
Public PlaDescr As String
Public PlaPai As PlaInfo
Public Nivel As Integer
End Class
Private lista As List(Of PlaInfo)
Private Function ListarPla() As List(Of PlaInfo)
...
End Function
Private Sub FormTeste_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.lista = ListarPla()
End Sub
Private Sub AdicionarNo(ByRef treeView As TreeView, ByVal descr As String, ByVal id As String, ByVal nivel As Integer)
Dim classPlaInfo As New PlaInfo With {.PlaConta = id, .PlaDescr = descr, .PlaPai = Nothing, .Nivel = nivel}
Me.lista.Add(classPlaInfo)
CarregarTreeView(treeView)
End Sub
Private Sub CarregarTreeView(ByRef treeView As TreeView)
...
' Lembrar de limpar os nós do TreeView
treeView.Nodes.Clear()
...
End Sub
End Class
Att.
Ari C. Raimundo
- Editado Ari C. Raimundo segunda-feira, 19 de outubro de 2009 00:07 Exemplo
Ari não deu certo !
Não dá nenhum erro, mas não inseri nenhum novo nó.
Meu arquivo ClassTreeView.vb
Public Class ClassTreeView Public Class PlaInfo Public PlaConta As String Public PlaDescr As String Public PlaPai As PlaInfo Public Nivel As Integer End Class Public lista As List(Of PlaInfo) Public Function ListarPla() As List(Of PlaInfo) Dim lista As New List(Of PlaInfo) lista.Add(New PlaInfo With {.PlaConta = "1", .PlaDescr = "RECEITAS", .Nivel = 1, .PlaPai = Nothing}) lista.Add(New PlaInfo With {.PlaConta = "1.01", .PlaDescr = "RECEITAS OPERACIONAIS", .Nivel = 2, .PlaPai = Nothing}) lista.Add(New PlaInfo With {.PlaConta = "1.01.01", .PlaDescr = "CLIENTES", .Nivel = 3, .PlaPai = Nothing}) lista.Add(New PlaInfo With {.PlaConta = "1.01.02", .PlaDescr = "CLIENTES DUVIDOSOS", .Nivel = 3, .PlaPai = Nothing}) lista.Add(New PlaInfo With {.PlaConta = "1.02", .PlaDescr = "OUTRAS RECEITAS", .Nivel = 2, .PlaPai = Nothing}) lista.Add(New PlaInfo With {.PlaConta = "1.02.01", .PlaDescr = "RECEITAS ESPECIAIS", .Nivel = 3, .PlaPai = Nothing}) lista.Add(New PlaInfo With {.PlaConta = "2", .PlaDescr = "DESPESAS", .Nivel = 1, .PlaPai = Nothing}) lista.Add(New PlaInfo With {.PlaConta = "2.01", .PlaDescr = "DESPESAS FIXAS", .Nivel = 2, .PlaPai = Nothing}) lista.Add(New PlaInfo With {.PlaConta = "2.01.01", .PlaDescr = "IMPOSTOS", .Nivel = 3, .PlaPai = Nothing}) lista.Add(New PlaInfo With {.PlaConta = "2.01.01.01", .PlaDescr = "IPI", .Nivel = 4, .PlaPai = Nothing}) lista.Add(New PlaInfo With {.PlaConta = "2.02", .PlaDescr = "DESPESAS EXTRAS", .Nivel = 2, .PlaPai = Nothing}) ListarPla = lista End Function Public Sub CarregarTreeView(ByVal TreeView As TreeView) ' lista itens Dim lista = ListarPla() ' loop na lista para buscar o pai For Each plaInfo In lista ' chave do pai Dim chavePai As String = "" If plaInfo.PlaConta.Contains(".") Then chavePai = plaInfo.PlaConta.Substring(0, plaInfo.PlaConta.LastIndexOf(".")) End If ' busca pelo pai Dim pai = (From plaPai In lista _ Where plaPai.PlaConta = chavePai _ Select plaPai).SingleOrDefault() ' verifica se o pai foi encontrado If pai IsNot Nothing Then plaInfo.PlaPai = pai End If Next plaInfo ' inicializa edição da treeView TreeView.BeginUpdate() ' limpa treeView TreeView.Nodes.Clear() ' ordena lista pelo nível lista.Sort(Function(x, y) x.Nivel.CompareTo(y.Nivel)) ' adiciona nós For Each plaInfo In lista If (plaInfo.PlaPai Is Nothing) Then TreeView.Nodes.Add(plaInfo.PlaConta, plaInfo.PlaDescr) Else Dim treeNodePai = TreeView.Nodes.Find(plaInfo.PlaPai.PlaConta, True) If (treeNodePai IsNot Nothing) Then treeNodePai(0).Nodes.Add(plaInfo.PlaConta, plaInfo.PlaDescr) End If End If Next plaInfo ' finaliza edição da treeView TreeView.EndUpdate() End Sub Public Sub AdicionarNó(ByRef treeView As TreeView, ByVal descr As String, ByVal id As String, ByVal nivel As Integer) Dim classPlaInfo As New PlaInfo With {.PlaConta = id, .PlaDescr = descr, .PlaPai = Nothing, .Nivel = nivel} Me.lista.Add(classPlaInfo) CarregarTreeView(treeView) End Sub End Class
E o Form1.Vb
Public Class Form1 Dim classTreeview As New ClassTreeView() Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load classTreeview.lista = classTreeview.ListarPla() classTreeview.CarregarTreeView(Me.TreeView1) End Sub Private Sub menu_Adicionar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles menu_Adicionar.Click classTreeview.AdicionarNó(Me.TreeView1, "Teste", "1.01.01.01", 4) End Sub End Class
Rafael Fernandes D OrazioRafael,
Na verdade a maneira como você está fazendo não está correta, mas vou ajudá-lo. Faça o seguinte:
1 - Comente a linha abaixo.
'Dim lista = ListarPla()
2 - Comente a linha abaixo:
'' ordena lista pelo nível
'lista.Sort(Function(x, y) x.Nivel.CompareTo(y.Nivel))
e substitua pelo código abaixo:
' ordena lista pelo nível e pela conta
Dim l = From q In lista _
Order By q.Nivel, q.PlaConta _
Select q
lista = l.ToList()
Att.
Ari C. Raimundo- Marcado como Resposta rafaeldorazio quarta-feira, 21 de outubro de 2009 01:35