Treeview of Checkbox

2019-07-11 23:54发布

I have created a user control consists of a checkbox control and a string which holds another value I would like to save for each checkbox.

The user is able to select or deselect the checkboxes.

public partial class UserControl1 : UserControl
{
    private CheckBox c = new CheckBox();
    private string EAType;
}

However, there are a lot of them and the Form layout looks messy.
Therefore, I would like to classify them by criteria, organizing them in a treeview.

This is quite easy to set the treeview to checkbox-treeview, but, as mentioned, I have another string to store for each.

Is a usercontrol treeview possible? If yes, how?
Any other ideas are welcome...

1条回答
老娘就宠你
2楼-- · 2019-07-12 00:43

Do you need a UserControl just to store a string?

To add custom information to a Control you always have Tag property and to add custom information to a TreeNode you have TreeNode.Tag property (there you can store what you want, a class or directly your string).

foreach (var obj in objects)
    treeView.Nodes.Add(new TreeNode { Text = obj.Title, Tag = obj.Value });

In this example I have an hypothetical collection objects, Title property will determine TreeNode caption and I store another custom value (from Value property) into TreeNode.Tag property. If you want you can directly store object itself:

foreach (var obj in objects)
    treeView.Nodes.Add(new TreeNode { Text = obj.Title, Tag = obj });

To access them you'll need to cast to proper type, for example (with strings):

var checkedNodes = treeView.Nodes.Cast<TreeNode>().Where(x => x.Checked);
var selectedValues = checkedNodes.Select(x => Convert.ToString(x.Tag));

Or, with objects:

var selectedValues = treeView.Nodes
    .Cast<TreeNode>()
    .Where(x => x.Checked)
    .Select(x => (YourObject)x.Tag);

Finally note that you may even use other list types:

  • For a simple list of values you can use ListBox with checkboxes. Each item is an object and then it can be anything you want, just override ToString() to provide proper display text.
  • For a more complex list (or with more items you want to organize in groups) you can use a ListView. Same technique we saw for TreeView, each ListViewItem has a Tag property you can use to store additional information. If you need just one level (multiple groups with a set of items) it may be more convenient than a tree view because customization is easier.

Whichever list you choose or you don't choose and you go with a plain CheckBox you don't really need a UserControl, in every control you have a Tag property for this purpose and for more complex situations you can derive directly from right control (CheckBox, for example) and add properties/methods you need. UserControl is (usually) used for composition when you need to have a control made of multiple ones for example to reuse some complex UI.

查看更多
登录 后发表回答