Reputation: 55
I am reading values from a serial port and would like to place these values in various textboxes on my form.
The textboxes are called:
tbMasterParam0,
tbMasterParam1,
tbMasterParam2,
...
tbMasterParam15
I would like to use the fact that they have a numeric naming structure and call them like they were arrays. Is this possible?
I have attached the code to give some context.
Otherwise I am just running a switch/case but this is becoming quite bulky. Surely I can do this in a few lines.
private void displayBoardValue(byte[] BoardParameters)
{
uint measurement;
string value;
measurement = (uint)(BoardParameters[3] + (BoardParameters[2] << 8));
value = measurement.ToString();
this.Controls[("tbMasterParam" + boardManager.parameter_id)].Text = value;
}
I seem to be getting a null reference exception
Upvotes: 2
Views: 62
Reputation: 186823
I'd rather extract a method:
public TextBox FindTextBox(int index)
{
// Find corresponding TextBox here
// Note .Find(..., true) - scan not only controls on the form,
// but all the child panels, groupboxes etc.
return Controls.Find("tbMasterParam" + index.ToString(), true).First() as TextBox;
}
...
private void displayBoardValue(byte[] BoardParameters)
{
uint measurement;
string value;
measurement = (uint)(BoardParameters[3] + (BoardParameters[2] << 8));
value = measurement.ToString();
FindTextBox(boardManager.parameter_id).Text = value;
}
Edit: as far as I can see from the comments, the problem is to scan not only form itself, but child panels, group boxes etc. In that case, you need Controls.Find(, true)
.
Upvotes: 3
Reputation: 1010
If I am not mistaken, you can achieve this by using the Find
method.
Like this:
this.Controls.Find()
You might need to cast it to a TextBox
.
Upvotes: 1