1

Is there any way to set the properties of the objects from string. For example I have "FullRowSelect=true" and "HoverSelection=true" statements as string for ListView property.

How to assign these property along with their values without using if-else or switch-case statments? Is there any SetProperty(propertyName,Value) method or similar for this?

8 Answers 8

3

Try this:

private void setProperty(object containingObject, string propertyName, object newValue)
{
    containingObject.GetType().InvokeMember(propertyName, BindingFlags.SetProperty, null, containingObject, new object[] { newValue });
}
Sign up to request clarification or add additional context in comments.

Comments

2

You can use reflection to do this:

myObj.GetType().GetProperty("FullRowSelect").SetValue(myObj, true, null);

Comments

1

You can do this with reflection, have a look at the PropertyInfo class's SetValue method

 YourClass theObject = this;
 PropertyInfo piInstance = typeof(YourClass).GetProperty("PropertyName");
 piInstance.SetValue(theObject, "Value", null);

Comments

1

Try this:

PropertyInfo pinfo = this.myListView.GetType().GetProperty("FullRowSelect");
if (pinfo != null)
    pinfo.SetValue(this.myListView, true, null);

Comments

1

First variant is to use reflection:

    public class PropertyWrapper<T>
    {
        private Dictionary<string, MethodBase> _getters = new Dictionary<string, MethodBase>();

        public PropertyWrapper()
        {
            foreach (var item in typeof(T).GetProperties())
            {
                if (!item.CanRead)
                    continue;

                _getters.Add(item.Name, item.GetGetMethod());
            }
        }

        public string GetValue(T instance, string name)
        {
            MethodBase getter;
            if (_getters.TryGetValue(name, out getter))
                return getter.Invoke(instance, null).ToString();

            return string.Empty;
        }
    }

to get a property value:

var wrapper = new PropertyWrapper<MyObject>(); //keep it as a member variable in your form

var myObject = new MyObject{LastName = "Arne");
var value = wrapper.GetValue(myObject, "LastName");

You can also use Expression class to access properties.

Comments

0

There isn't such a method, but you could write one using reflection.

Comments

0

You can look at Reflection. Its possible to find property and set its value thanks to this. But you need to parse your string yourself. And it may be problem geting valid value of correct type from string.

Comments

0

This can be accomplished with reflection, for example look at this question.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.