Home » C# Programming

Using reflection in a user control

I would like to use reflection to set a property of another control on the form from the user control I am building (ie. set the ImageIndex of another button from my user control). Can anyone give me an idea on how to do this?




6 Answers Found


Answer 1

I'm sorry it's not quite clear what you're asking. Do you want to change the property  of another control  while your builing a user  control OR do you want to build a control that when the user interacts with it it changes the properties of another control?


Answer 2

Why do you think you need to use reflection?

Answer 3

I would like to do the second. When the user  interacts with the user contro at runtime it changes a property  (specifically the ImageIndex) of other controls (more than 1). I am assuming I need to use reflection  to set  the properties of the other controls as I have not found a way to make a property in my user control  that stores a collection of object references of the other controls.

If there is a better way of accomplishing this please enlighten me :-)


Answer 4

See reply to Pantelis4499. Thanks

Answer 5

What is that collection of controls you want to change? All the controls? Controls from a list of names?

- TopLevelControl.Controls retrieves all controls on the form.

- TopLevelControl.Controls.Find(name, true) retrieves all controls with a specific name.

You can then cast the control  to whichever type you need and set  its ImageIndex to the value you want.

If you want to set the ImageIndex property  but you don't know the type of the control, you can use reflection  on the controls retrieved:

control.GetType().GetProperty("ImageIndex").SetValue(control, value, null);


Answer 6

This is exactly what I was looking for! Thanks a bunch.




<< Previous      Next >>

Microsoft   |   Windows   |   Visual Studio   |   Sharepoint   |   Azure