So, a System.Windows.Forms.Control has a Controls property of type Control.ControlCollection. I have a control on a form that has a bunch of small sub-controls in this collection. These sub-controls have a label and a text identifier that’s the field name from a database.
I need to be able to go back into the Controls collection and find the controls by name. ControlCollection has a public virtual Control this[string key] { get; } and a public virtual bool ContainsKey(string key), so it looks like I should be able to look them up.
However, the Add function (public virtual void Add(Control value)) doesn’t take a key string, just the System.Windows.Forms.Control you’re adding, and all my calls to ContainsKey are returning false.
Figuring something on the Control has to be overridden to be the key (since only the Control is passed), I tried overriding ToString() to return the database field name (which I’m wanting to use for the lookup), but ContainsKey still returns false when I know a control for the field specified is present.
The documentation for this[string key] { get; } says the key parameter is “The name of the control to retrieve from the control collection.” The Control does not have a Name property I can override, its only Name property contains the class name, which will be the same for every control I’m adding. The documentation for ContainsKey(string key) says the key parameter is “The key to locate”, which is even less helpful.
Found the answer, but I already wrote all this up so I might as well publish it and then self-answer in case someone else might find it useful…
While I can’t override the
Nameproperty, it’s {get;set;}, not pure {get;} as I stupidly assumed. So if I set theNameof my control to the database field name before I add it to theControlscollection, I can look it up as expected.The answer was in the summary docs of the
Control[] Find(string key, bool searchAllChildren)method, not the docs for the functions I was going to use:“Searches for controls by their System.Windows.Forms.Control.Name property and builds an array of all the controls that match.”