Search for controls by control name reflection, control name reflection
Because the understanding of. net is not too deep, we can only make the following level:
Find the desired Reflection Property Information:
PropertyInfo ^ getPropertyInfo (Type ^ t, String ^ pName ){
PropertyInfo ^ pInfo;
While (t! = Nullptr ){
PInfo = t-> GetProperty (pName, BindingFlags: DeclaredOnly | BindingFlags: Public | BindingFlags: Instance );
If (pInfo! = Nullptr)
{
Return pInfo;
}
T = t-> BaseType;
}
Return nullptr;
}
Search from a Component, and then check whether its sub-Component is a control named compName. If yes, return nullptr. If no, return nullptr.
// Get a component by it's name, the component is in comp
Component ^ getComponentByName (String ^ compName, Component ^ comp ){
If (nullptr = comp)
{
Return comp;
}
// If this component is the right one, then return it
Type ^ t = comp-> GetType ();
PropertyInfo ^ pInfo = t-> GetProperty ("Name ");
If (pInfo! = Nullptr & compName-> Equals (dynamic_cast <String ^> (pInfo-> GetValue (comp, nullptr ))))
{
Return comp;
}
// Search this component's children Controls
Component ^ retComp;
PInfo = getPropertyInfo (t, "Controls ");
If (pInfo! = Nullptr)
{
System: Collections: IList ^ list = safe_cast <System: Collections: IList ^> (pInfo-> GetValue (comp, nullptr ));
If (list! = Nullptr)
{
For (int I = 0; I <list-> Count; I ++)
{
If (nullptr! = (RetComp = getComponentByName (compName, safe_cast <Component ^> (list [I])
{
Return retComp;
}
}
}
}
// Search this component's children Items
PInfo = getPropertyInfo (t, "Items ");
If (pInfo! = Nullptr)
{
System: Collections: IList ^ list = safe_cast <System: Collections: IList ^> (pInfo-> GetValue (comp, nullptr ));
If (list! = Nullptr)
{
For (int I = 0; I <list-> Count; I ++)
{
If (nullptr! = (RetComp = getComponentByName (compName, safe_cast <Component ^> (list [I])
{
Return retComp;
}
}
}
}
Return nullptr;
}
In VS2008, how does one find existing controls in the form based on the control name?
There seems to be a drop-down text box on the property Panel, where you can select it!
In VB6, how can I find controls by control name?
Honestly, there are better ways to implement your functions...
1. Use the control array.
2. Use a collection object.
Both methods can implement your functions.
The control array is very convenient, just like the array.
Set is better. Add a TextBox-type control to it as an element.