0

enter image description here

Here i have made some code to get my categories in TreeView like --Core ---Core Subcat --Non Core ---Non Core Subcat

My code only shows me:

  1. Core
  2. Non Core

Please help me out with this code. please correct me if i'm wrong.

Thank You.

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;

        }

Result Expected in TreeView:

-Core
--Core Subcat
-Non Core
--Non Core Subcat
Shaggy
  • 67
  • 2
  • 12

2 Answers2

0

I think its better that you change your "Sql Select". If you get your data in TreeView model, you can show it very simple.

In this sample "rn" field will help you so much.

CodeMan
  • 671
  • 6
  • 13
0
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);
        }
    }

}
Shaggy
  • 67
  • 2
  • 12
  • Querying database in a loop, Really?! – Reza Aghaei Jan 06 '19 at 16:05
  • This worked for me.. Is that bad habit ? Please help – Shaggy Jan 06 '19 at 16:35
  • It's a really bad idea to load data in a loop from SQL server and in this case you just need to load data once, then using a recursive function add nodes to tree. [My answer](https://stackoverflow.com/a/54062217/3110834) shares a good solution for the problem using a generic method. If you want to learn something (maybe hard at start), read may answer and the linked post as well, otherwise ignore my answers and live happy! – Reza Aghaei Jan 07 '19 at 04:50
  • as i'm new to programming your answer is little hard but i'll try to understand that. Thank you for your good support. – Shaggy Jan 07 '19 at 11:49
  • No problem, read the inline comments in the post. Also make sure you read the linked post as well. – Reza Aghaei Jan 07 '19 at 12:18
  • Sir, please check my edited answer. I have implemented your code but it does not give any answer. please correct me. – Shaggy Jan 07 '19 at 12:51
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/186301/discussion-between-shaggy-and-reza-aghaei). – Shaggy Jan 07 '19 at 12:59