I have an existing Window Forms application. The application has a property grid. The values of the properties are set by the user at runtime. What I would like to do is determine from code the current value of any given property. I have had partial success. I am able to get the Category as well as the property name information. I am having difficulty getting the current value of the properties as set by the user, as well as two other related questions.
The code I am using is as follows:
// ICustomTypeDescriptor Interface Implementation
public AttributeCollection GetAttributes()
{
return TypeDescriptor.GetAttributes(GetType());
}
public string GetClassName()
{
return TypeDescriptor.GetClassName(GetType());
}
public string GetComponentName()
{
return TypeDescriptor.GetComponentName(GetType());
}
public TypeConverter GetConverter()
{
return TypeDescriptor.GetConverter(GetType());
}
public EventDescriptor GetDefaultEvent()
{
return TypeDescriptor.GetDefaultEvent(GetType());
}
public PropertyDescriptor GetDefaultProperty()
{
return TypeDescriptor.GetDefaultProperty(GetType());
}
public object GetEditor(Type editorBaseType)
{
return TypeDescriptor.GetEditor(GetType(), editorBaseType);
}
public EventDescriptorCollection GetEvents(Attribute[] attributes)
{
return TypeDescriptor.GetEvents(GetType(), attributes);
}
public EventDescriptorCollection GetEvents()
{
return TypeDescriptor.GetEvents(GetType());
}
public PropertyDescriptorCollection GetProperties(Attribute[] attributes)
{
// ... This returns a list of properties.
PropertyDescriptorCollection pdc = TypeDescriptor.GetProperties(GetType(), attributes);
PropertyDescriptor[] arr = new PropertyDescriptor[pdc.Count];
pdc.CopyTo(arr, 0);
PropertyDescriptorCollection propertyCollection = new PropertyDescriptorCollection(arr);
ModifyProperties(propertyCollection); // modifies which properties are visible
// temporary code to get the program to print out the properties
foreach (PropertyDescriptor pd in propertyCollection)
{
Print("input category = "+pd.Category);
Print("input display name = "+pd.DisplayName);
Print("input name = "+pd.Name);
// Print("input value = "+pd.GetValue(Input).ToString()); <--- Does NOT work
}
return propertyCollection;
}
public PropertyDescriptorCollection GetProperties()
{
return TypeDescriptor.GetProperties(GetType());
}
public object GetPropertyOwner(PropertyDescriptor pd)
{
return this;
}
My questions are:
-
How can I get the values of the properties? For example, I have a property aspect ratio. Its display name is Aspect Ratio and its name is aspectRatio. Its value is 5. How can I retieve this via code at runtime?
-
How can I order the properties. I have tried to use the above approach to ordering the properties but the ordering failed. I am not sure how best to proceed.
Any suggestions would be greatly appreciated. Thank you.
Maybe this
If you have custom objects you want to get a nice string from you could add a helper method like below:
Demo class: