0

I have 10 Labels and a Object with 10 Properties. I want to have a Loop that put on the first Label the first Property of the object, on the second Label the second Property from the object and so on..

My problem is to change the property Name of the object with the loop because it isn't a string...

_Label1.Fill = object .Color1;     
_Label2.Fill = object .Color2;    
_Label3.Fill = object .Color3; 
Andrei
  • 55,890
  • 9
  • 87
  • 108
Bulli
  • 115
  • 1
  • 8
  • 1
    Take a look at arrays. – Leri Aug 06 '13 at 08:37
  • Put the ten property values into an array; do the same with the labels. Then loop over the arrays in parallel and set. – Jon Aug 06 '13 at 08:37
  • 4
    It sounds to me like you should have a collection of labels and a collection of colours. Having properties of Foo1, Foo2 etc is always a bad sign. – Jon Skeet Aug 06 '13 at 08:37
  • I agree with Jon Skeet 's comment. Try to use 2 collections and a loop which will set the appropriate properties to the labels. – Younes Aug 06 '13 at 08:40
  • Use reflection by hardcoded property access, see the link: [Get property value from string using reflection in C#][1] [1]: http://stackoverflow.com/questions/1196991/get-property-value-from-string-using-reflection-in-c-sharp – neo-ray Aug 06 '13 at 08:48
  • @neo-ray for future info in comments use `[comment](link)` – Sayse Aug 06 '13 at 08:51
  • 1
    (Joke) I didn't know `System.Object` had been expanded with `static` members `Color1`, `Color2`, `Color3`. – Jeppe Stig Nielsen Aug 06 '13 at 08:58

1 Answers1

3

You could achieve this with reflection like this:

for(int i= 1; i<= 10; i++)
{
     Label[i-1].Fill = (Color)object.GetType().GetProperty("Color" + i.ToString()).GetValue(object, null);
}

I assume, that you have the labels in an array or list and that the Color Properties are of type Color

Romano Zumbé
  • 7,893
  • 4
  • 33
  • 55