【问题标题】:Populate treeview without ID填充没有 ID 的树视图
【发布时间】:2018-01-24 12:30:01
【问题描述】:

我有如下数据表;

TYPE   NAME

FR     APPLE
FR     BANANA
TR     FISTIK
GR     ENGINE
GR     TANK

我想使用上面的数据表制作一个如下所示的树形视图;

-FR
 -- APPLE
 -- BANA
-TR
 -- FISTIK
-GR 
 -- ENGINE
 -- TANK

如果可能的话,我想在不使用 ID 的情况下填充它,PARENT_ID。

有可能这样做吗?

【问题讨论】:

  • 有可能,但显示一些代码...
  • @Nino 我使用“在 winform 上填充树视图而不使用 id”进行了很多搜索,但没有任何结果
  • 如果您展示代码以查看类的结构或查看如何获取数据,我可以指导您(或编写代码)来完成您的任务。但是,如果没有代码,它只会是猜测。

标签: c# winforms datatable treeview


【解决方案1】:

尝试以下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;


namespace WindowsFormsApplication9
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            DataTable dt = new DataTable();
            dt.Columns.Add("Type", typeof(string));
            dt.Columns.Add("NAME", typeof(string));

            dt.Rows.Add(new object[] {"FR", "APPLE"});
            dt.Rows.Add(new object[] {"FR", "BANANA"});
            dt.Rows.Add(new object[] {"TR", "FISTIK"});
            dt.Rows.Add(new object[] {"GR", "ENGINE"});
            dt.Rows.Add(new object[] {"GR", "TANK"});

            populateTreeview(dt);
            treeView1.ExpandAll();
        }
        //Open the XML file, and start to populate the treeview
        private void populateTreeview(DataTable dt)
        {
            var groups = dt.AsEnumerable().GroupBy(x => x.Field<string>("Type"));
            treeView1.Nodes.Clear();

            foreach(var group in groups)
            {
                TreeNode node = treeView1.Nodes.Add(group.Key);
                foreach(string name in group.Select(x => x.Field<string>("NAME")))
                {
                    node.Nodes.Add(name);
                }
            }
        }

    }
}

【讨论】:

  • 哦,我明白你为什么这么说,我将数据表读取为数据库。我的错。
猜你喜欢
  • 1970-01-01
  • 2014-11-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-10
  • 1970-01-01
相关资源
最近更新 更多