Search code examples
c#.netloopsiterationnumericupdown

How to get all dynamic numericupdown values in c# windows forms


I want to get the values from the NumericUpDown that is generated through the for loop which will be iterated N times. However in my code, I can only get the first NumericUpDown value and it is triggered through a button click.

Code for displaying the NumericUpDown tools:

for (int i = 0; i < 6; i++) // should be i < n
{
    NumericUpDown note = new NumericUpDown();
    note.Name = "Note" + i.ToString();
    note.Location = new System.Drawing.Point(20, 40 + (40 * i));
    note.Size = new System.Drawing.Size(40, 25);
    note.Maximum = new decimal(new int[] { 10, 0, 0, 0 });
    this.Controls.Add(note);
}

Code for getting the values:

var numericUpDown = this.Controls["note0"] as NumericUpDown;
var value = numericUpDown.Value;
MessageBox.Show(value.ToString());

How can I get all the values? Thank you so much for all your help.


Solution

  • I hope that you are looking for something like this:

    foreach (NumericUpDown ctlNumeric in this.Controls.OfType<NumericUpDown>())
    {
        var value = ctlNumeric.Value;
        MessageBox.Show(value.ToString());
    }