当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - 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());

}

网友答案:

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);
}
网友答案:

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

分享给朋友:
您可能感兴趣的文章:
随机阅读: