如何从数据库填充TreeView [英] How to Fill TreeView from DataBase

查看:65
本文介绍了如何从数据库填充TreeView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好朋友

我有一个表(Hesab),其中有3个字段(ID,名称,父亲ID),并使用EF.
我想在treeview中填写这张表

树必须像这样填充
A
-D
--F
--E
-H
B
-C
--G

我创建了此类

Hi friends

I have a table(Hesab) whit 3 fields (ID,Name,FatherID), and use EF.
and i want fill this table in treeview

the tree must be fill like this
A
-D
--F
--E
-H
B
-C
--G

I Created this class

 class Hesabs:Hesab
    {
    public Hesabs()
    {
        AllHesab = new ObservableCollection<hesab>();
    }
    public ObservableCollection<hesab> AllHesab { get; set; }
           }

</hesab></hesab>



和viewmodel



and viewmodel

 public ObservableCollection<hesabs> AllHesab { get; set; }
    public ObservableCollection<hesabs> FirstHesab { get; set; }

    public ViewModelHesabs()
    { 
        CRMEntities crm=new CRMEntities();

        var ls = from h in crm.Hesab
                 where (h.FatherID == null)
                 select h;
        ObservableCollection<hesabs> hes = new ObservableCollection<hesabs>();
        foreach (Hesab hh in ls.ToList())
        {
            var ls2 = from h in crm.Hesab
                      where (h.FatherID == hh.ID)
                      select h;
            Hesabs hesab = new Hesabs();
            hesab.Name = hh.Name;
            hesab.ID = hh.ID;
            hesab.AllHesab = new ObservableCollection<hesab>(ls2.ToList());
            hes.Add(hesab);
        }
        FirstHesab = hes;
    }

</hesab></hesabs></hesabs></hesabs></hesabs>


和xaml


and xaml

<treeview itemssource="{Binding FirstHesab}">
     <treeview.itemtemplate>
     <hierarchicaldatatemplate itemssource="{Binding AllHesab}" datatype="         {x:Type local:Hesabs}">
             <stackpanel orientation="Horizontal">
                 <textblock text="{Binding Name}" tag="{Binding ID}" />
             </stackpanel>
         </hierarchicaldatatemplate>
     </treeview.itemtemplate>
 </treeview>



但只能填充2级.:(



but fill 2 level only.:(

推荐答案



记录中的父亲ID是否是指向同一表的链接,即您是否具有自引用实体?我认为代码中就是这种情况,但请确保.

您的问题似乎是您选择了每个"h",然后遍历并填充了每个h的孩子-我认为您将需要递归执行此操作,否则您将只获得第一个级别的孩子们.
Hi,

Is the FatherID in the record a link to the same table, i.e. do you have a self-referencing entity? I think this is the case from the code but want to be sure.

You''re problem appears to be that you select each ''h'' , then go through and fill each h''s children - I think you will need to do this operation recursively, otherwise you will only get the first level of children.



是的,我有一个自引用实体.
我将代码更改为
Hi ,
Yes, i have a self-referencing entity.
i change the code to
foreach (Hesab hh in crm.Hesab.ToList())


这篇关于如何从数据库填充TreeView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆