views:

60

answers:

1

In TreeView you can add a tag to the node. In a checkbox ... you can't. I found TreeViews useful because this allowed me to use the name for the "display" value and the text for additional information. Example the name as "Google" and the tag as "http://google.com".

How is it possible to do this with checkboxes? I know a checkbox accepts and object, so could I simply create a new class that allows a string and a tag, and add do it that way?

Or is there an easier way?

+2  A: 

Both System.Windows.Forms.CheckBox (WinForms) and System.Windows.Controls.CheckBox (WPF) have a Tag property with public get and set accessors. This is because in each case there is a base class providing such a property (in the case of WinForms it is Control.Tag and in the case of WPF it is FrameworkElement.Tag).

Note that the Tag property is typed as an object. Anything that can be assigned to an instance of object you can assign to a Tag property. In particular, you could assign an instance of string. When you read the Tag property you have to cast it back to a string:

// checkBox is CheckBox
string s = (string)checkBox.Tag;

Alternatively, you could say

// checkBox is CheckBox
string s = checkBox.Tag.ToString();

Lastly, you could inherit from CheckBox and provide a Tag property that is typed as a string that hides the base implementation:

class MyCheckBox : CheckBox {
    public new string Tag { get; set; }
}
Jason
+1 In fact this applies to any class or control derived from `Control`, not just CheckBoxes.
Jon Seigel