Wednesday, January 26, 2011

Tree View Using database

Step 1Create two database tables ParentMaster and ChildMaster

Step 2 : Now that we have created our tables, open Microsoft Visual Studio 2005 and create and Asp.net 2.0 WebForm.

Step 3 : Add the following LOC (Line of code) at the start of your programs along with other using keywords.
                   using System.Data.SqlClient;

Step 4 : Place a TreeView control on your WebForm.


          Now double click your page, point to Page_Load event and write fillTree();

                             protected void Page_Load(object sender, EventArgs e)
                               {
                                    fillTree();
                               }



Step 5 : Now the real thing starts. In this step we will populate our TreeView1 control using our two tables ParentMaster and ChildMaster.

     Create a function fillTree()
    
        private void fillTree()
           {
            string connectionstring = ConfigurationManager.ConnectionStrings["your connectionstring name"].ConnectionString;
            SqlConnection mycon = new SqlConnection(connectionstring);
            mycon.Open();
            SqlCommand mycmd = new SqlCommand("Select * from ParentMaster", mycon);
            SqlDataReader dr = mycmd.ExecuteReader();
            mycmd.Dispose();
            string[,] ParentNode = new string[100, 2];
            int count = 0;
            while (dr.Read())
            {
                ParentNode[count,0]=dr.GetValue(dr.GetOrdinal("ParentId")).ToString();
                ParentNode[count++, 1] = dr.GetValue(dr.GetOrdinal("ParentName")).ToString();
            }
            dr.Close();
            for (int loop = 0; loop < count; loop++)
            {
                TreeNode root = new TreeNode();
                root.Text = ParentNode[loop, 1];
                root.NavigateUrl = "Default.aspx";

                SqlCommand childcmd = new SqlCommand("Select * from ChildMaster where ParentId='" + ParentNode[loop, 0] + "'", mycon);
                SqlDataReader childdr = childcmd.ExecuteReader();
                while (childdr.Read())
                {
                    TreeNode croot = new TreeNode();
                    croot.Text = childdr.GetValue(childdr.GetOrdinal("ChildName")).ToString();
                    croot.NavigateUrl = "Grid.aspx";
                    root.ChildNodes.Add(croot);
                }
                childdr.Close();

                TreeView1.Nodes.Add(root);
                TreeView1.CollapseAll();
            }
        }
    }


Also see my other blogs: Reset Table id to zero in sql server
                                                                Get Primary key of gridview on edit commant