Reputation: 2726
How to get/set property of Control
(in this case Button
)?
I tried on this way:
Type t = Type.GetType("System.Windows.Forms.Button");
PropertyInfo prop = t.GetType().GetProperty("Enabled");
if (null != prop && prop.CanWrite && prop.Name.Equals("button1"))
{
prop.SetValue(t, "False", null);
}
but t is null. What is wrong here?
Upvotes: 0
Views: 577
Reputation: 186803
First, you need the instance to set property at, it's button1
:
object instance = button1;
you may want to find it, e.g. let's scan all open forms of MyForm
type, and look for Button
with "button1"
Name
:
using System.Linq;
...
object instance = Application
.OpenForms
.OfType<MyForm>()
.SelectMany(form => form.Controls.Find("button1", true))
.OfType<Button>()
.FirstOrDefault();
...
Then we are ready for Reflection:
var prop = instance.GetType().GetProperty("Enabled");
if (prop != null && prop.CanWrite && prop.PropertyType == typeof(bool))
// we set false (bool, not string "False") value
// for instance button1
prop.SetValue(instance, false, null);
Edit: If you want to obtain Type
from string
via Type.GetType(...)
you want assembly qualified name:
string name = typeof(Button).AssemblyQualifiedName;
And you'll get something like
System.Windows.Forms.Button, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Demo:
Type t = Type.GetType(
@"System.Windows.Forms.Button, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
MessageBox.Show(t.Name);
Upvotes: 2