Habib Salim
Habib Salim

Reputation: 13

Setting property values dynamically

I am using a PivotGrid(DevExpress). I want to set AppearancePrint property settings in a for loop.

How do i use the variable type for properties such as Cell in the example below?

so instead of

grid.AppearancePrint.Cell.BackColor = Color.White;
grid.AppearancePrint.Cell.BackColor2 = Color.LightBlue;

I want to do this:

//datarow example <PrintAppearance Type="Cell" Font="Tahoma,8,Regular" BackColor="White" BackColor2="Light Grey"/>

foreach (DataRow dr in appearances)          
{
   string type = dr["Type"].ToString();
   grid.AppearancePrint.[type].BackColor = Color.FromName(dr["BackColor"].ToString());
   grid.AppearancePrint.[type].BackColor2 = Color.FromName(dr["BackColor2"].ToString());
}

Upvotes: 1

Views: 668

Answers (2)

Bradley Smith
Bradley Smith

Reputation: 13621

This is essentially a form of script-parsing, and you'll need to use reflection in order to do it. For example:

foreach (DataRow dr in appearances) {
   string type = dr["Type"].ToString();

   PropertyInfo propertyForType = grid.AppearancePrint.GetType().GetProperty(type);
   object objectForProperty = propertyForType.GetValue(grid.AppearancePrint, null);

   PropertyInfo propertyForBackColor = objectForProperty.GetType().GetProperty("BackColor");
   PropertyInfo propertyForBackColor2 = objectForProperty.GetType().GetProperty("BackColor2");

   propertyForBackColor.SetValue(objectForProperty, Color.FromName(dr["BackColor"].ToString()), null);
   propertyForBackColor2.SetValue(objectForProperty, Color.FromName(dr["BackColor2"].ToString()), null);
}

Upvotes: 2

Basic
Basic

Reputation: 26766

I'm not familiar with your exact problem but at a glance, it seems you'll need to use reflection as you won't know the type until runtime - In case you're not familiar with reflection, it will allow you to examine the object (and more importantly the properties on it)

See here for a possible solution

Upvotes: 0

Related Questions