Introduction
This is about how to get the control object on a form by passing the object's name. This can be useful in a situation where you want to perform a action on object
by getting the reference to the object using object's name. I used this method to get the control object after getting the object's name according to a algorithm.
Using the code
private void ClickPublicButton(string name)
{
try
{
if (string.IsNullOrEmpty(name))
{
throw new ArgumentNullException("ClickPublicButton: Needs a button name");
}
else
{
System.Reflection.FieldInfo field = this.GetType().GetField(name);
if (field == null)
{
throw new ArgumentException(string.Format(
"ClickPublicButton: Button \"{0}\" not found", name));
}
else
{
Button bnew = field.GetValue(this) as Button;
if (bnew == null)
{
throw new ArgumentException(string.Format(
"ClickPublicButton: \"{0}\" is not a button", name));
}
else
{
bnew.PerformClick();
}
}
}
}
catch (ArgumentNullException a)
{
MessageBox.Show(a.Message);
}
catch (ArgumentException b)
{
MessageBox.Show(b.Message);
}
}
But remember Type.GetField("objectName")
only gets public fields. So the object we are trying to get reference should be declared as public.
If the object is declared as private we have to use the two parameter version in the GetField()
method.
private void ClickPrivateButton(string name)
{
try
{
if (string.IsNullOrEmpty(name))
{
throw new ArgumentNullException("ClickPrivateButton: Needs a button name");
}
else
{
System.Reflection.FieldInfo field = this.GetType().GetField(name,
System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
if (field == null)
{
throw new ArgumentException(string.Format(
"ClickPrivateButton: Button \"{0}\" not found", name));
}
else
{
Button bnew = field.GetValue(this) as Button;
if (bnew == null)
{
throw new ArgumentException(string.Format(
"ClickPrivateButton: \"{0}\" is not a button", name));
}
else
{
bnew.PerformClick();
}
}
}
}
catch (ArgumentNullException a)
{
MessageBox.Show(a.Message);
}
catch (ArgumentException b)
{
MessageBox.Show(b.Message);
}
}