Problem with NumericUpDown type
-
17-09-2020 - |
Question
When i do something like this:
public static void BindData<T>(this System.Windows.Forms.Control.ControlCollection controls, T bind)
{
foreach (Control control in controls)
{
if (control.GetType() == typeof(System.Windows.Forms.TextBox) || control.GetType().IsSubclassOf(typeof(System.Windows.Forms.TextBox)))
{
UtilityBindData(control, bind);
}
else
{
if (control.Controls.Count == 0)
{
UtilityBindData(control, bind);
}
else
{
control.Controls.BindData(bind);
}
}
}
}
private static void UtilityBindData<T>(Control control, T bind)
{
Type type = control.GetType();
PropertyInfo propertyInfo = type.GetProperty("BindingProperty");
if (propertyInfo == null)
propertyInfo = type.GetProperty("Tag");
// rest of the code....
where controls is System.Windows.Forms.Control.ControlCollection
and among controls on the form that is passed as a parameter to this piece of code there are NumericUpDowns, i cant find them in the controls collection (controls=myForm.Controls), but there are controls of other types(updownbutton, updownedit). The problem is that i want to get NumericUpDown's Tag property and just cant get it when using that recursive method of checking form controls.
Solution
The Tag
property is defined by the Control
class.
Therefore, you don't need reflection at all; you can simply write
object tag = control.Tag;
Your code isn't working because the control's actual type (eg, NumericUpDown
) doesn't define a separate Tag
property, and GetProperty
doesn't search base class properties.
By the way, in your first if
statemeant, you can simply write
if (control is TextBox)