Populate a Combo Box with a Tree View data and syn

2019-08-03 22:51发布

Hello Stackoverflow Contributors,

I have a Combo Box "CmboExpenseType" with no data in at the moment.

I also have a Tree View "TVProperties" with the following data.

I'd like to get the Parent Nodes from this tree view into the "CmboExpenseType".

So when the user clicks on the Combo Box they will see the parent nodes "Income, Entertainment, Transportation & Others" and then I can program the Child Nodes to go into another Combo Box.

I'm not trying to get a Combo Box into my Tree View.

I have only tried this code at this time. But it worked to no avail.

CmboExpenseType.Items.Add(TVProperties);

Would it be worth me moving the nodes into a list or dictionary?

I have some ideas on possible ways after of getting all Parent Nodes in, like a possible foreach loop. I'm just stuck on adding the data from the Tree View into my Combo Box.

Any help would be fantastic. If more information is need please don't hesitate to tell me.

2条回答
虎瘦雄心在
2楼-- · 2019-08-03 23:23

As you've probably discovered, there's no databinding for a treeview so they can't share a datasource.

To get the treeview to change when the combo changes, we can use a little databinding magic:

private void Form1_Load(object sender, EventArgs e)
{
    var nodes = TVProperties.Nodes;
    CmboExpenseType.DisplayMember = "Text";
    CmboExpenseType.DataSource = nodes;
}

Then on the selected value change of the combo, just pull out the selected value:

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

    TVProperties.SelectedNode = node; 
}
查看更多
Bombasti
3楼-- · 2019-08-03 23:30

If you want to take the node text from existing TreeView, you can do the following

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

CmboExpenseType.DataSource = list;

Not sure about how you populate the TreeView in first place, It will be easy to populate the ComboBox at the same time with only first level node data.

查看更多
登录 后发表回答