I have function that changes the property of controls based on the control name and the input command.
public void SetControl(string ControlName, string Operation)
{
Control Control = this.Controls.Find(ControlName, true)[0];
switch (Operation)
{
case "ok":
Control.BackColor = Color.Green;
Control.ForeColor = Color.Black;
break;
case "error":
Control.BackColor = Color.Red;
Control.ForeColor = Color.Blue;
break;
}
}
now I am wondering if there is any way to pass property name as well? of course I can do something like this:
if (propertyname=="ForeColor")
{Control.ForeColor = Color.Black;}
but then I should do this for all of the properties that I am going to change! Is there anyway to find and change the property based on its name?
Yes. This is precisely what reflection does.
var value = Control.GetType().GetProperty(propertyname).GetValue(Control, null);
Then set your value
Control.GetType().GetProperty(propertyname).SetValue(Control, valueToSet);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.