views:

63

answers:

2

Hi,

I get child properties of an object with this code,

PropertyDescriptorCollection childProperties = TypeDescriptor.GetProperties(theObject)[childNode.Name].GetChildProperties();

think that "theObject" variable is a TextBox and I try to set TextBox.Font.Bold = true;

I use this code for main properties and it works when I customize for main properties. But when I access the child properties,

I get an error which is "Object reference not set to an instance of an object.".

foreach (PropertyDescriptor childProperty in childProperties)
        {
            foreach (XmlAttribute attribute in attributes)
            {
                if (childProperty.Name == attribute.Name)
                {

                    if (!childProperty.IsReadOnly)
                    {

                        object convertedPropertyValue = ConverterHelper.ConvertValueForProperty(attribute.Value, childProperty);

                        childProperty.SetValue(theObject, convertedPropertyValue); //exception throw here

                        break;
                    }
                }
            }
        }
+1  A: 

It looks like you are passing the wrong object to SetValue - on the face of it it looks like you get something like:

<TextBox>
  <Font Bold="true"/>
</Textbox>

And then you get the Font property of the text box and the Bold property of the font and then you try to assign the value true to the Bold property of TextBox. Obviously this is not going to work.

Maybe something like this:

PropertyDescriptor objProp = TypeDescriptor.GetProperties(theObject)[childNode.Name];
PropertyDescriptorCollection childProperties = objProp.GetChildProperties();

foreach (PropertyDescriptor childProperty in childProperties) {
    foreach (XmlAttribute attribute in attributes) {
        if (childProperty.Name == attribute.Name && !childProperty.IsReadOnly) {
            Object convertedPropertyValue = converterHelper.ConvertValueForProperty(attribute.Value, childProperty);
            childProperty.SetValue(objProp.getValue(theObject), convertedPropertyValue);
        }
    }
}

Note that the context for setting properties of the child object is the child object and not the parent object.

Guss
I can get attributes and values from xml. there is no problem there but now I get this error : "Object does not match target type." when SetValue method.
Can
I think I found my mistake, and I assumed that childObject is the instance of `Font` but it is not. I've reedited the answer, try it this time.
Guss
Yes. thank you so much.it works.
Can
Glad to help. I'd also appreciate it if you can accept my answer :-)
Guss
A: 

I can get attributes and values from xml. there is no problem there but now I get this error : "Object does not match target type." when SetValue method.

Can