Skip to content

Using Recursion I Want to Display the list of Contents to th

Jenkins J

Asked Apr 8, 2016, 12:54 AM EDT1 answer
Share
LinkedInX
C#
Using Recursion I Want to Display the list of Contents to the datagridview in c# winforms.I tried by the below But as a result in datagridview Only Parent values displaying no Child Values Displayed




        public class PageItem
        {
            public int Id { get; set; }
            public int ParentId { get; set; }
            public string MenuText { get; set; }
            public List<PageItem> Childs { get; set; }
        }
 
 
Conditions:-
 
C#
        public List<PageItem> GetPageItems()
        {
            List<PageItem> pageItems = new List<PageItem>();
            SqlCeConnection conn = new SqlCeConnection(@"Data
           Source=D:\database\Employee.mdf;");
SqlCeCommand cmd = new SqlCeCommand("SELECT Id, ParentId, MenuTitle
Code
            FROM Page", conn);
            conn.Open();
            SqlCeDataReader rdr = cmd.ExecuteReader();

             var allItems = new List<PageItem>();


            while (rdr.Read())
            {
               var item = (new PageItem()
                          {
                              Id = Convert.ToInt32(rdr["Id"]),
                              ParentId = Convert.ToInt32(rdr["ParentId"]),
                              MenuText = rdr["MenuTitle"].ToString()

                          });

               allItems.Add(item);
               var parent = allItems.Where(pi => pi.Id == item.ParentId).SingleOrDefault();

               if (parent == null)
               {
                  pageItems.Add(item);


               }
               else
               {
                   if (parent.Childs == null)
                       parent.Childs = new List<PageItem>();
                   parent.Childs.Add(item);


               }
            }

            rdr.Close();
            conn.Close();

            return pageItems;
        }
 
 
Form Load:-
 
C#
        private void Form1_Load(object sender, EventArgs e)
        {
            GetPageItems();
            this.dataGridView1.DataSource = GetPageItems();

            this.comboBox1.DataSource = GetPageItems();
            this.comboBox1.DisplayMember = "MenuText";
            this.comboBox1.ValueMember = "ParentId";
        }





From the above code I got an output like this:-
 
parent 0
parent 1
parent 2
parent 3
 
I Need an Output Like this:-
 
Parent 0
Child 1
Child 2
Child 3
Child 3.1
Child 3.2
Child 3.3
Parent 1
Parent 2
Parent 3
 
Thank You..

1 Answer

Know the answer? Post it. Somebody with the same question will find it here.

  • Surya Kant
    0
    Check at
     var parent = allItems.Where(pi => pi.Id == item.ParentId).SingleOrDefault();
    this line you doing some thing mistake check with by putting break point at that line.
    Hope you get solution after doing this.
    0