Get/Set control's property, PropertyHelper class

I was playing with the intellisence and I found something interesting. I decided to make a little class to show you what I found. It can be useful. It's thread safe.

The class:

 public class PropertyHelperpublic PropertyHelper(Form helperForm)
{
this.HelperForm = helperForm;}public Form HelperForm
{
get;
set;
}
public void SetProperty(Control control, string property, object value)
{
try
{
if (this.HelperForm.InvokeRequired)
{
this.HelperForm.BeginInvoke(new MethodInvoker(delegate{Type type = control.GetType();
PropertyInfo info = type.GetProperty(property);
info.SetValue(control, value, null);
}
)
);
}
else
{
Type type = control.GetType();
PropertyInfo info = type.GetProperty(property);
info.SetValue(control, value, null);
}
}
catch (Exception ex)
{
throw ex;
}
}
public object GetProperty(Control control, string property){object returnObject = null;
try
{
if (this.HelperForm.InvokeRequired)
{
this.HelperForm.BeginInvoke(new MethodInvoker(delegate{Type type = control.GetType();
PropertyInfo info = type.GetProperty(property);
returnObject = info.GetValue(control, null);
}
)
);
}
else{Type type = control.GetType();
PropertyInfo info = type.GetProperty(property);
returnObject = info.GetValue(control, null);
}
return returnObject;
}
catch (Exception ex)
{
throw ex;
}
} }

How to use it:

    PropertyHelper helper = new PropertyHelper(this);

    helper.SetProperty(textBox1, "Text", "Hey"); //Change the text of a textbox.
    helper.SetProperty(panel1, "BackColor", Color.Red); //Change the back color of a panel.
    helper.SetProperty(this, "Text", "Welcome"); //Change text of a form.
}


Similar Articles