I have a row of NumericUpDown boxes with a Label in a Form and I would like to display the total of all the NumericUpDown values in the Label.
I know I can add a small piece of code in each NumericUpDown on ValueChange that will then return the sum in the label but I want to try and avoid repeating the same piece of code.
Is there a way of writing a class that can be called into the NumericUpDown on ValueChange to make it easier to maintain.
Current piece of code that is repeated For Each NumbericUpDown:
private void num_Personal_NumbericUpDown1_ValueChanged(object sender, EventArgs e)
{
this.lbl_Personal_label1.Text = (this.num_Personal_NumbericUpDown1.Value
this.num_Personal_NumbericUpDown2.Value
this.num_Personal_NumbericUpDown3.Value
this.num_Personal_NumbericUpDown4.Value
this.num_Personal_NumbericUpDown5.Value).ToString();
}
CodePudding user response:
You can create separated method for NumericUpDown
controls ValueChanged
events:
private void NumericUpDown_ValueChanged(Object sender, EventArgs e)
{
// Do the sum and display magic. It will be continued below.
}
And add it as delegate
to rule them all, instead of calling your controls manually:
foreach (NumericUpDown control in Controls.OfType<NumericUpDown>())
{
control.ValueChanged = NumericUpDown_ValueChanged;
}
So currently there is so all that remains is to define the logic in your method, for example using LINQ Sum()
method:
private void NumericUpDown_ValueChanged(Object sender, EventArgs e)
{
decimal sum = Controls.OfType<NumericUpDown>().Sum(control => control.Value);
lbl_Personal_label1.Text = sum.ToString();
}
And here you go! Changing Value
of any NumericUpDown
in your form will trigger ValueChanged
event which will calculate current sum of controls values.
EDIT: to make my answer to comment more readable:
Is there a way of specifying which NumericUpDown's in the code?
You can create any specific controls collection that implements IEnumerable
to make it still easy, e.g. an array. Just put here chosen controls:
var someControlsArray = new NumericUpDown[]
{
num_Personal_NumbericUpDown2,
num_Personal_NumbericUpDown3 // etc
};
decimal chosenControlsSum = someControlsArray.Sum(control => control.Value);