So yesterday on my commute home I was thinking (it's an hour each way, so there's lots of time for it).
Many developers have asked about getting the name of a control in the CF, and it's just not nicely exposed. I thought, wouldn't it be nice to be able to get the name of a control if I have an instance of it (like in an event handler) or to be able to get an instance of a control if I know the string name?
With a little work using reflection I came up with this (and for the record, reflection f'ing rocks!), which will be in the SDF release:
public class ControlEx
{
public static Control GetControlByName(Control Parent, string Name)
{
FieldInfo info = Parent.GetType().GetField(Name,
BindingFlags.NonPublic | BindingFlags.Instance |
BindingFlags.Public | BindingFlags.IgnoreCase);
if(info == null) return null;
object o = info.GetValue(Parent);
if(o == null) return null;
return (Control)o;
}
public static string GetControlName(object SourceControl)
{
FieldInfo[] fi = ((Control)SourceControl).Parent.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance |
BindingFlags.Public | BindingFlags.IgnoreCase);
foreach(FieldInfo f in fi)
{
if(f.GetValue(((Control)SourceControl).Parent).Equals(SourceControl))
return f.Name;
}
return null;
}
}