首页 > 解决方案 > 动态填充 TreeView... 像类别 > 父类别

问题描述

在此处输入图像描述

在这里,我编写了一些代码来获取 TreeView 中的类别,例如 --Core ---Core Subcat --Non Core ---Non Core Subcat

我的代码只显示:

  1. 非核心

请帮我解决这个代码。如果我错了,请纠正我。

谢谢你。

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

标签: c#winforms

解决方案


我认为最好更改“Sql Select”。如果您在TreeView模型中获取数据,则可以非常简单地显示它。

在此示例中,“rn”字段将对您有很大帮助。


推荐阅读