Given that WinForms declares these objects as fields of the form, though,
you could do it via Reflection:
public object GetObjectByInstanceName(string fieldname)
{
Type t = this.GetType();
FieldInfo fi = t.GetField(fieldname, BindingFlags.Instance |
BindingFlags.NonPublic);
if (fi == null)
return null;
else
return fi.GetValue(this);
}
Assuming GetObjectByInstanceName is a member function implemented on the
form; if it's not, make sure you pass the form instance in and change the
calls to GetValue and this.GetType() accordingly.
Note that since these fields are private, the assembly will need to be
running in a relatively trusted (that is, must be granted the permissions to
Reflect on private elements) zone in order to execute.
Ted Neward
Author, Instructor, Consultant
Java, .NET, Web services
http://www.neward.net/ted
Also reach me at [EMAIL PROTECTED]
> -----Original Message-----
> From: Unmoderated discussion of advanced .NET topics. [mailto:ADVANCED-
> [EMAIL PROTECTED] On Behalf Of J. Merrill
> Sent: Wednesday, June 29, 2005 2:26 PM
> To: [email protected]
> Subject: Re: [ADVANCED-DOTNET] Can I get reference to an object by its
> name?
>
> Frans is right in the case you actually asked about -- the name of a local
> variable can't get you to a reference to the object whose reference is
> stored in that local variable.
>
> However, in the context of a Windows Forms app (which I suspect is your
> situation given your use of a TextBox control in the example), you can
> examine the elements of the Controls array of the form, and check each to
> see if the Name property is what you want. (You would need to do this
> recursively, as the control you're looking for could be "under" any of the
> form's controls.)
>
> At 04:31 PM 6/29/2005, Frans Bouma wrote
> >> Is there a way to get a reference to an object by its name?
> >>
> >> E.g.
> >> TextBox st1 = new TextBox();
> >>
> >> Object o = GetObjectByInstanceName("st1");
> >
> > No, if you want that, you should store the reference to the
> object in a structure that's accessable by the code which wants
> >to execute GetObjectByInstanceName.
> >
> > Frans
>
>
> J. Merrill / Analytical Software Corp
>
> ===================================
> This list is hosted by DevelopMentor. http://www.develop.com
>
> View archives and manage your subscription(s) at
> http://discuss.develop.com
===================================
This list is hosted by DevelopMentorĀ® http://www.develop.com
View archives and manage your subscription(s) at http://discuss.develop.com