Reputation: 558
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++;
}
Upvotes: 2
Views: 169
Reputation: 117027
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.
Upvotes: 4
Reputation: 4833
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));
}
Upvotes: 0