简体   繁体   中英

Binding the database data to tree view using c# in winforms applications

I have a table named as categories....with columns...

                                category_id
                                categoryname

I want to represent the category names only in tree view ....

is it possible to bind the category names to tree view like this...

                           Category 
                              categoryname 1
                              categoryname 2
                              categoryname 3

is it possible using c#.. I am using windows applications....

would any one pls help on this one...

Many thanks in advance..

in more web forms you can simply binding dataset to your treeview control but in win forms there is no any databing. in this sample i inheritance System.Windows.Forms.TreeView class and write my own code to binding dataset to Win Treeview control and I use it in my application more than 3 years and it works fine.

First: you must create class as Custom_Tree_View.cs and add below code into it

 public class Custom_Tree_View : System.Windows.Forms.TreeView
{
    DataSet dsMenu = new DataSet();
    public TreeNodeMouseClickEventHandler TreeNode_Click_Event;

    float FontSize = 9F;
    string FontName = "Tahoma";
    public string Data_Key_Member;
    public string Data_Key_Value;
    private ImageList imageList1;
    private System.ComponentModel.IContainer components;
    public string Data_Parent_Key;


    public bool ShowCheckBox = false;

    public Custom_Tree_View()
    {
        this.Font = new System.Drawing.Font(this.FontName, this.FontSize);          
        this.NodeMouseClick += NodeMouseClicked;
    }


    public void CreateMenu(DataSet _dsMenu)
    {
        try
        {

            this.Nodes.Clear();

            if (_dsMenu == null) return;
            this.CheckBoxes = this.ShowCheckBox;
            this.dsMenu = _dsMenu;

            string Filter = this.Data_Parent_Key + " IS NULL";
            foreach (DataRow drTemp in dsMenu.Tables[0].Select(Filter))
            {
                Create_Parent_Tree_Node(drTemp[0].ToString());
            }



        }
        catch (Exception ex)
        {
            throw ex;
        }
    }




    private void Create_Parent_Tree_Node(string strMenu)
    {
        try
        {

            TreeNode mmru = new TreeNode(GetMenu_Details_Title(strMenu));
            mmru.Name = strMenu;
            if (dsMenu.Tables[0].Select(this.Data_Parent_Key + "='" + strMenu + "'").Length > 0)
            {

                this.Nodes.Add(mmru);
                foreach (DataRow drTemp in dsMenu.Tables[0].Select(this.Data_Parent_Key + "='" + strMenu + "'"))
                {
                    Create_Child_Tree_Node(mmru, drTemp[0].ToString());
                }
            }
            else
            {
                mmru.ForeColor = System.Drawing.Color.Red;
                this.Nodes.Add(mmru);
            }


        }
        catch (Exception ex)
        {
            throw ex;
        }
    }


    private string Create_Child_Tree_Node(TreeNode mnuItem, string strMenu)
    {
        try
        {
            if (dsMenu.Tables[0].Select(this.Data_Parent_Key + "='" + strMenu + "'").Length > 0)
            {
                TreeNode mmru = new TreeNode(GetMenu_Details_Title(strMenu));

                mmru.Name = strMenu;
                mnuItem.Nodes.Add(mmru);
                foreach (DataRow drTemp1 in dsMenu.Tables[0].Select(this.Data_Parent_Key + "='" + strMenu + "'"))
                {

                    Create_Child_Tree_Node(mmru, drTemp1[0].ToString());
                }
            }
            else
            {
                TreeNode mmru = new TreeNode(GetMenu_Details_Title(strMenu));
                mmru.Name = strMenu;
                mmru.ForeColor = System.Drawing.Color.Red;

                mnuItem.Nodes.Add(mmru);
                return strMenu;
            }
            return strMenu;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    private string GetMenu_Details_Title(string TreeNode_ID)
    {

        try
        {              
            return dsMenu.Tables[0].Select(this.Data_Key_Value + "=" + TreeNode_ID + "")[0][this.Data_Key_Member].ToString();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    private bool GetMenuEnable(string TreeNode_ID)
    {
        try
        {
            if (dsMenu.Tables[0].Select(this.Data_Key_Value + "='" + TreeNode_ID + "'")[0][3].ToString() == "Y")
                return true;
            else
                return false;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }


    public TreeNode SelectedTreeNode;


    private void NodeMouseClicked(object sender, TreeNodeMouseClickEventArgs e)
    {
        try
        {                

            if (dsMenu.Tables[0].Select(this.Data_Parent_Key + "='" + e.Node.Name + "'").Length > 0)
            {
                return;
            }
            else
            {
                if (this.TreeNode_Click_Event != null)
                    TreeNode_Click_Event(sender, e);
            }


        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

    private void InitializeComponent()
    {
        this.components = new System.ComponentModel.Container();
        this.imageList1 = new System.Windows.Forms.ImageList(this.components);
        this.SuspendLayout();
        // 
        // imageList1
        // 
        this.imageList1.ColorDepth = System.Windows.Forms.ColorDepth.Depth8Bit;
        this.imageList1.ImageSize = new System.Drawing.Size(16, 16);
        this.imageList1.TransparentColor = System.Drawing.Color.Transparent;
        // 
        // Custom_Tree_View
        // 
        this.Font = new System.Drawing.Font("Tahoma", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(178)));
        this.ItemHeight = 25;
        this.LineColor = System.Drawing.Color.Black;
        this.RightToLeft = System.Windows.Forms.RightToLeft.Yes;
        this.RightToLeftLayout = true;
        this.NodeMouseClick += new System.Windows.Forms.TreeNodeMouseClickEventHandler(this.Custom_Tree_View_NodeMouseClick);

        this.ResumeLayout(false);

    }

    private void Custom_Tree_View_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
    {
        try
        {
            if (e.Node.Checked == true)
            {

                foreach (TreeNode Node in e.Node.Nodes)
                {

                    Node.Checked = true;
                }
            }



            if (e.Node.Checked == false)
            {

                foreach (TreeNode Node in e.Node.Nodes)
                {

                    Node.Checked = false;
                }
            }






        }
        catch (Exception ex)
        {

            MessageBox.Show(ex.Message);
        }
    }

}

second:
in your project adding New Control onto your forms and write below code to binding dataset to treeview control

DataSet Menu_Ds = new DataSet();              
Menu_Ds =  GetMyDataSet();
this.custom_Tree_View_Menu.Data_Key_Member = "Menu_Details_Title";
this.custom_Tree_View_Menu.Data_Key_Value ="Menu_Details_Id";
this.custom_Tree_View_Menu.Data_Parent_Key = "Menu_Details_Parent";
this.custom_Tree_View_Menu.CreateMenu(Menu_Ds);

Notice: in your dataset you must have tree field Title,ID and Parent_Id field to create treeview correctly

I hope this post will be useful for all and I am sorry for my bad English

This is something you cannot achieve in Windows Forms using standard tree view control, but it's feasible.

The best approach is to derive your own control from TreeView , create DataSource property. After assigning DataSource your control should build it's structure based on the data. You may need some additional properties to describe column with node text and column with id and parent id.

If you want to have more complete approach you should also consider subscribing to some additional event to DataSource object and react to DataSource event changes.

Interesting design decision is whether you want to build the whole tree at once or wait for the user to expand the given node.

You can also find at least 2 working examples on CodeProject:

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        MenuDS ds = new MenuDS();

        CategoryTableAdapter daCategory = new CategoryTableAdapter();
        ProductTableAdapter daProduct = new ProductTableAdapter();

        daCategory.Fill(ds.Category);
        daProduct.Fill(ds.Product);

        if (ds.Tables[0].Rows.Count > 0)
        {
            TreeView1.Nodes.Clear();
            foreach (DataRow dr in ds.Category.Rows)
            {
                TreeNode mastreNode = new TreeNode(dr["cateNAme"].ToString(), dr["Id"].ToString());
                TreeView1.Nodes.Add(mastreNode);
                TreeView1.CollapseAll();

                DataTable dt = daProduct.GetDataBy(Convert.ToInt32((dr["Id"])));

                foreach (DataRow drNew in dt.Rows)
                {
                    TreeNode childNode = new TreeNode(drNew["prodName"].ToString(), drNew["Id"].ToString());
                    childNode.NavigateUrl = "~/ProductDetails.aspx?Id=" + drNew["Id"].ToString();
                    mastreNode.ChildNodes.Add(childNode);

                }
            }
        }
    }



}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM