Home > Net >  C# Windows Forms Application: Change behavior of all instances of a control
C# Windows Forms Application: Change behavior of all instances of a control

Time:09-30

I would like to change the increment values and decimal places for all of my numeric updowns.

I know I can do this individually this is what I'm dealing with, most of these will be hidden in a practical use case, max case

CodePudding user response:

How are you creating all those NumericUpDown controls? If you're doing it in the designer, then that's the place to set the properties to what you want.

If you're creating them programmatically, then change the properties there instead.

If for some reason you can't do either of those things (but why?) then you could use reflection to set them all like so. This method assumes that it will be a member of the form containing the NumericUpDown controls, and that the controls are all at the top level (i.e. not contained in a Panel or other such container control):

void setNumericUpDownProperties()
{
    foreach (var numericUpDown in this.Controls.OfType<NumericUpDown>())
    {
        numericUpDown.DecimalPlaces = 2;
        numericUpDown.Increment = 0.01M;
    }
}

(This requires using System.Linq;)

You would call that after the call to InitializeComponent() in the form's constructor.

  • Related