Search code examples
c#.netcomboboxtreeview

Populating a Combo box with Tree View Data


Earlier Today I asked a question about getting Tree view data into a Combo Box.

    public MainForm()
    {
        InitializeComponent();

            var list = TVProperties.Nodes
                   .Cast<TreeNode>()
                   .Select(x => x.Text)
                   .ToList();

        CmboExpenseType.DataSource = list;

        var Clist = TVProperties.Nodes[0].Nodes
       .Cast<TreeNode>()
       .Select(x => x.Text)
       .ToList();

        CmboExpenseDetail.DataSource = Clist;

    }

The Above Code is what I use when starting the program. This helps me get the Parent & Child Node but when the parent node is changed the child node isn't changing.

This is the image of the two Combo Boxes I have now the top one displays the Parent Node and the Child Node.

I have tried to use Fred's answer in the SelectedIndexChange on the Combo Box but it's not working or I don't understand the way it should.

private void CmboExpenseType_SelectedIndexChanged(object sender, EventArgs e)
{
    var node = CmboExpenseType.SelectedItem as TreeNode;
    if(node == null)
        return;

    TVProperties.SelectedNode = node; 
}

This is my Tree View and some Child Nodes. I was wondering if I was doing something wrong code wise and if there was any help that you could give me.


Solution

  • You need to set focus on treeview:

    private void CmboExpenseType_SelectedIndexChanged(object sender, EventArgs e)
    {
        var node = CmboExpenseType.SelectedItem as TreeNode;
        if(node == null)
            return;
    
        TVProperties.Focus();
        TVProperties.SelectedNode = node; 
    }