Заполнить TreeView динамически ... Как категория> Родительская категория - PullRequest
0 голосов
/ 06 января 2019

enter image description here

Здесь я сделал некоторый код, чтобы получить мои категории в TreeView как --core --- Core Subcat - Не ядро --- не основной субкадр

Мой код показывает только мне:

  1. Основной
  2. без сердечника

Пожалуйста, помогите мне с этим кодом. пожалуйста, поправьте меня, если я ошибаюсь.

Спасибо.

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["InventoryManagerConnectionString"].ConnectionString);

        private void btnLoadNodes_Click(object sender, EventArgs e)
        {

            DataTable dt = this.GetData("SELECT * FROM tblProductCategories WHERE Cat_ParentCat =0");
            this.PopulateTree(dt, 0, null);

        }

        private void PopulateTree(DataTable dtParent, int parentId, TreeNode treeNode)
        {
            foreach (DataRow row in dtParent.Rows)
            {
                TreeNode child = new TreeNode
                {
                    Text = row["Cat_Name"].ToString(),
                    Tag = row["Cat_ID"]
                };
                if (parentId == 0)
                {
                    treeViewCat.Nodes.Add(child);
                    DataTable dtChild = this.GetData("SELECT * FROM tblProductCategories WHERE Cat_ParentCat="+ child.Tag);
                }
                else
                {
                    treeNode.Nodes.Add(child);
                }
            }
        }

        private DataTable GetData(string query)
        {
            DataTable dt = new DataTable();

            SqlCommand cmd = new SqlCommand(query);

            SqlDataAdapter sda = new SqlDataAdapter();

            cmd.CommandType = CommandType.Text;
            cmd.Connection = con;
            sda.SelectCommand = cmd;
            sda.Fill(dt);
            return dt;

        }

Результат, ожидаемый в TreeView:

-Core
--Core Subcat
-Non Core
--Non Core Subcat

Ответы [ 2 ]

0 голосов
/ 06 января 2019
public partial class TreeTest : Form
{
    public TreeTest()
    {
        InitializeComponent();

        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["InventoryManagerConnectionString"].ConnectionString);



        var dt = new DataTable();
        var source = dt.AsEnumerable();

        var nodes = GetTreeNodes(
            /*The data table*/
            source,
            /*How detect if a row is a root row*/
            (r) => r.Field<int>("Cat_ParentCat") == 0,
            /*How to find child rows for a row*/
            (r, s) => s.Where(x => r["Cat_ID"].Equals(x["Cat_ParentCat"])),
            /*How to create a node from a row*/
            (r) => new TreeNode { 
            Text = r.Field<string>("Cat_Name"),
           Tag = r.Field<int>("Cat_ID")
    }
    );
            treeViewCat.Nodes.AddRange(nodes.ToArray());
    }

    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["InventoryManagerConnectionString"].ConnectionString);

    private void btnLoadNodes_Click(object sender, EventArgs e)
    {
        string query = "SELECT * FROM tblProductCategories WHERE Cat_ParentCat =0";
        GetData(query);
    }


    public DataTable GetData( string command)
    {
        var dt = new DataTable();
        using (var da = new SqlDataAdapter(command, con))
            da.Fill(dt);
        return dt;
    }


        private IEnumerable<TreeNode> GetTreeNodes<T>(
            IEnumerable<T> source,
            Func<T, Boolean> isRoot,
            Func<T, IEnumerable<T>, IEnumerable<T>> getChilds,
            Func<T, TreeNode> getItem)
        {
            IEnumerable<T> roots = source.Where(x => isRoot(x));
            foreach (T root in roots)
                yield return ConvertEntityToTreeNode(root, source, getChilds, getItem); ;
        }
    private TreeNode ConvertEntityToTreeNode<T>(
        T entity,
        IEnumerable<T> source,
        Func<T, IEnumerable<T>, IEnumerable<T>> getChilds,
        Func<T, TreeNode> getItem)
    {
        TreeNode node = getItem(entity);
        var childs = getChilds(entity, source);
        foreach (T child in childs)
            node.Nodes.Add(ConvertEntityToTreeNode(child, source, getChilds, getItem));
        return node;
    }


    private void btnGetNode_Click(object sender, EventArgs e)
    {
        try
        {
            MessageBox.Show(treeViewCat.SelectedNode.Tag.ToString());
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

}
0 голосов
/ 06 января 2019

Я думаю, что лучше, чтобы вы изменили свой «Выбор Sql». Если вы получаете данные в модели TreeView , вы можете показать их очень просто.

В этом примере поле «рН» вам очень поможет.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...