2

I have created a number of controls that are derived from base controls. As part of these extended controls I have added a number of properties. One of these properties is a unique ID that helps me to bind it to a database value.

I need to be able to search for this control by UniqueID, a property that only my derived controls have (note that all controls on the form are my derived controls, and all of them have UniqueID as a property). Reflection jumps to mind but I cannot find an example.

Ryan Hargreaves
  • 267
  • 3
  • 16

1 Answers1

2

Use Enumerable.OfType<T> to filter out controls of your specific type and then you can query against the specific property, something like:

var controls = this.Controls.OfType<YourControl>().Where(r => r.UniqueId == someValue);

Remember this only searches the controls at root level, if you are interested in finding nested controls then you have to use a recursive approach. See: How to get ALL child controls of a Windows Forms form of a specific type (Button/Textbox)?

Community
  • 1
  • 1
Habib
  • 219,104
  • 29
  • 407
  • 436
  • Good Answer. How does it vary if each of the controls is different? For example, if I have a MyTextBox : TextBox and MyComboBox : ComboBox. Would I need to use Controls.OfType() ? – Ryan Hargreaves May 11 '16 at 14:12
  • Sure you can use the base class in that case, but If you use `Control` base class then it will not be limited to the classes you specified above, it will include other control classes as well, like Button etc. – Habib May 11 '16 at 14:16
  • 1
    That's actually Ok. The only controls on there are the ones I have created, all of which contain the property. Thanks for your help :) – Ryan Hargreaves May 11 '16 at 14:17
  • After testing this I have a Compile Time error, due to the fact that Control does not have the property I'm looking for. Since the controls don't derive from the same place, is there an alternative? – Ryan Hargreaves May 11 '16 at 14:31
  • @RyanHargreaves, if the controls do not derive from the same place, then you probably have to resort to reflection. – Habib May 11 '16 at 14:38
  • Do you have an example of that? – Ryan Hargreaves May 11 '16 at 14:40
  • One option would be to create your own BaseControl class derived from `Control` that has the UniqueID property and then derive all of your other controls from that class. Then you could use `Enumerable.OfType` and the property would always be there. Then you wouldn't have to resort to reflection. – Chris Dunaway May 11 '16 at 17:46
  • Better than using a common base class is defining an interface `IControlWithUniqueID`. Then have all your My* control classes implement that interface. You can then use `OfType()` as used in the answer. – NineBerry May 16 '16 at 11:52