TreeView for WinForms | ComponentOne
Data Binding / Self-Referencing
In This Topic
    Self-Referencing
    In This Topic

    TreeView can be bound with self-referencing data, that is, a single table or a list instead of multiple related tables or lists. With self-referencing data, the Parent-Child relationship for the records is set by defining KeyField and ParentKeyField properties where the Key field is used to identify the records and the ParentKey field is used to set the parent-child relationship. Here, the KeyField property sets a value specifying the key field of the data source bound to the TreeView control, while the ParentKeyField property sets a value representing the data source field identifying the parent record in the data source.

    TreeView in an app

    In the following example, we set the data source named EmployeesSelfRefDataSet and add columns to be displayed in the TreeView. Then, we created the parent-child relation between the records of the data source by setting KeyField and ParentKeyField properties to the ID and ChiefID fields respectively, in the data source as shown in the following code.

    To check the data in EmployeesSelfRefDataSet class, see TreeView product sample in the corresponding .NET version folder at Documents\ComponentOne Samples\WinForms\vx.x\TreeView\CS\BoundModeWithDataSet\Employees location on your system.

    C#
    Copy Code
    //loads a self ref dataset
    private void LoadDataSet()
    {
        ClearTreeView();
    
        //add columns
        var column = new C1TreeColumn();
        column.DisplayFieldName = "Post";
        column.HeaderText = "Post";
        c1TreeView1.Columns.Add(column);
        column = new C1TreeColumn();
        column.DisplayFieldName = "FirstName";
        column.HeaderText = "First name";
        c1TreeView1.Columns.Add(column);
        column = new C1TreeColumn();
        column.DisplayFieldName = "LastName";
        column.HeaderText = "Last name";
        c1TreeView1.Columns.Add(column);
    
        //set the key and parentkeyfield
        c1TreeView1.BindingInfo.KeyField = "ID";
        c1TreeView1.BindingInfo.ParentKeyField = "ChiefID";
    
        //set the data source
        c1TreeView1.BindingInfo.DataMember = "Employees";
        c1TreeView1.BindingInfo.DataSource = SamplesData.EmployeesSelfRefDataSet.GetData();
    
    }