Retrieve instance name using Reflection

J

JW

Dear NG,

I am writing a .NET CF forms app. that needs to dynamically configure
buttons on a form. Since the forms designer doesn't like component arrays I
am using ordinary instance names for each button (btn0, btn1 etc.) as
private members of the form class, but need to reference these from a loop
that is iterating through the button config. information (array).

My question is how can I loop through a collection of buttons with names
like "btn0, btn1 etc." calling methods on each as the loop executes?
Pseudo-CS would look something like:

string[] buttonNames = new string[]{"foo", "bar", "etc"};
Button current;
for (int i=0; i<buttonNames.Length; i++)
{
current = this.ReflectionMagic.GetInstance("btn" + i);
current.Text = buttonNames;
}

Please note that I have diligently RTFM & STFW to no avail, and so any help
would be greatly appreciated.

Thanks,

James.

PS. Please remove anti-spam for email replies.
 
M

Mattias Sjögren

James,
string[] buttonNames = new string[]{"foo", "bar", "etc"};
Button current;
for (int i=0; i<buttonNames.Length; i++)
{
current = this.ReflectionMagic.GetInstance("btn" + i);
current.Text = buttonNames;
}


Do you have to involve the name (as a string)? How about

Button[] buttons = {btn0, btn1};
foreach ( Button current in buttons )
{
...
}




Mattias
 
J

JW

Mattias,

Thanks for your reply. It would seem that my example simplified the problem
a little too much.

Along the lines of the MVC design pattern, a FormsMarshall class requests a
value object containing form configuration information (including a string
array containing button text information) and passes that object to a
generic form. The form constructor then needs to be able to loop through
the array assigning the text to the buttons according to the array index.

Having said all this, on reflection (pun intended ;), your response has made
me think I am making things too complicated. I can see now that each
generic form, along with the button declarations for the form designer,
could have a button array declared at the same time for use by looping
configuration code.

Thanks again for your help.

James.

Mattias Sjögren said:
James,
string[] buttonNames = new string[]{"foo", "bar", "etc"};
Button current;
for (int i=0; i<buttonNames.Length; i++)
{
current = this.ReflectionMagic.GetInstance("btn" + i);
current.Text = buttonNames;
}


Do you have to involve the name (as a string)? How about

Button[] buttons = {btn0, btn1};
foreach ( Button current in buttons )
{
...
}




Mattias
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top