2

I wish to assign values to NumericUpDowns which are named numericUpDown1, numericUpDown2, etc. What I wish to achieve is something like this:

for (int i = 0; i < readBuf.Length; i++)
{
    numericUpDown[i + 1].Value = Convert.ToDecimal(BitConverter.ToSingle(readBuf[i], startIndex: 0));             
}

What I tried doing is the method described here: Loop through Textboxes, but it doesn't give the expected results when I use it like this

var allNumUpDwn = this.GetChildControls<NumericUpDown>();
int i = 0;
foreach (NumericUpDown nud in allNumUpDwn)
{
    nud.Value = Convert.ToDecimal(BitConverter.ToSingle(readBuf[i], startIndex: 0));
    i++;
}
Community
  • 1
  • 1
Rikus Honey
  • 534
  • 1
  • 3
  • 17
  • What exactly the `readBuf` is? You have to debug your application. Insert breakpoints in the code and see what's going on. – Dmitry Dec 27 '15 at 01:10
  • @Dmitry I am reading memory from another process and changing it with a numericUpDown control, but sometimes the values change in the program and the numericUpDowns doesn't update so I need to read the memory again. – Rikus Honey Dec 27 '15 at 01:18

2 Answers2

4

I would use this kind of approach:

var nuds = new []
{
    numericUpDown1, numericUpDown2,
    numericUpDown3, numericUpDown4,
    numericUpDown5, numericUpDown6,
    // etc
};

for (int i = 0; i < readBuf.Length; i++)
{
    nuds[i].Value = Convert.ToDecimal(BitConverter.ToSingle(readBuf[i], startIndex: 0));
}

The big advantage here is that your code is compile-time checked, so that if you start deleting or renaming controls then you will have a compile error rather than a run-time error.

Enigmativity
  • 113,464
  • 11
  • 89
  • 172
  • I agree with Enigmativity. This approach is better unless your numericUpDowns are built dynamically. – serhiyb Dec 27 '15 at 01:08
  • @Enigmativity Ah I was hoping I could avoid the repetitiveness of writing each numericUpDown in an array, but if it's what needs to be done, it has to be done. Thanks for the answers! – Rikus Honey Dec 27 '15 at 01:15
  • @RikusHoney - You could always collect the array using `Controls.Find` and LINQ, but that would return you to a run-time error if there is one. – Enigmativity Dec 27 '15 at 03:48
0

You can try:

for (int i = 0; i < readBuf.Length; i++)
{
    ((NumericUpDown)Controls.Find("numericUpDown" + (i+1))).Value = Convert.ToDecimal(BitConverter.ToSingle(readBuf[i], startIndex: 0));             
}
serhiyb
  • 4,753
  • 2
  • 15
  • 24