TreeStructure of Database


Database Connection:
In class1.cs

public DataTable GetDataSource(string Query)
        {

            SqlConnection con = new SqlConnection();
            DataTable dt = new DataTable();
            con.ConnectionString = WebConfigurationManager.ConnectionStrings["company"].ConnectionString;
            con.Open();
            SqlDataAdapter da = new SqlDataAdapter(Query, con);
            da.Fill(dt);
            con.Close();
            return dt;

        }

In Default.aspx.cs

namespace treeview
{
    public partial class _Default : System.Web.UI.Page
    {

        Class1 connect = new Class1();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                RootLevel(Treeview1);// Treeview1 is the tree created in Default.aspx
            }
        }



        public void RootLevel(Control ctl)
        {

            string SQlQuery = "select table_Name from information_schema.tables where table_type='BASE TABLE'";//table name reterived
     


            DataTable dt = new DataTable();
            dt = connect.GetDataSource(SQlQuery);
            DataRow[] myrows;
            myrows = dt.Select();//index of table


            TreeView t1 = new TreeView();

            t1 = (TreeView)ctl;
            t1.Nodes.Clear();


            for (int p = 0; p < myrows.Length; p++)
            {// Create Parent Node

                TreeNode parentNode = new TreeNode();

                parentNode.Text = (string)myrows[p]["table_Name"];
                t1.Nodes.Add(parentNode);

             // Get Child Node

                string SQlQuery1 = "select *  from "+ parentNode.Text;

                DataTable dt1 = new DataTable();
                dt1 = connect.GetDataSource(SQlQuery1);
                DataRow[] cmyrows;
                cmyrows = dt1.Select();


                for (int c = 0; c < cmyrows.Length; c++)
                {
                    TreeNode childNode = new TreeNode();
                    TreeNode childNode1 = new TreeNode();
       
                    childNode.Text = (string)cmyrows[c][0];
                    childNode1.Text = (string)cmyrows[c][1];
                 
                    parentNode.ChildNodes.Add(childNode);
                    childNode.ChildNodes.Add(childNode1);
                 
                }
            }

       }
    }
}


Comments

Popular posts from this blog

How to retain the data annotations or class during modify a table in the database

Interview Questions

AJAX CONTROL