How to concatenate the contents of variable in the name of label and others variables?
//labels: lbl_01_temp, lbl_02_temp, lbl_03_temp
string XX;
double id_01_temp, id_02_temp, id_03_temp;
lbl_XX_temp.Text= "The Device " +XX+ "has" +id_XX_temp+" ℃";
How to concatenate the contents of variable in the name of label and others variables?
//labels: lbl_01_temp, lbl_02_temp, lbl_03_temp
string XX;
double id_01_temp, id_02_temp, id_03_temp;
lbl_XX_temp.Text= "The Device " +XX+ "has" +id_XX_temp+" ℃";
The clean way to concatenate values is to use String.Format
lbl_XX_temp.Text= String.Format("The Device {0} has {1} ℃", XX, id_XX_temp);
Maybe, I misunderstood the question. I think the OP wants to convert a string into a valid control right?
Web:
string lblSelected = String.Format("lbl_{0}_temp", XX);
Label lbl = (Label)this.FindControl(lblSelected);
lbl.Text = String.Format("The Device {0} has {1} ℃", XX, id_XX_temp);
WinForms:
string lblSelected = String.Format("lbl_{0}_temp", XX);
Control[] ctrl = this.Controls.Find(lblSelected, true);
Label lbl = ctrl[0] as Label;
lbl.Text = String.Format("The Device {0} has {1} ℃", XX, id_XX_temp);
String.Format is actually less performing than a straight string concatenation like your question poses. It's probably a matter of ticks and nanoseconds, but there is more overhead involved with String.Format than just saying a + b + c for string concatenation.
Personally, String.Format looks cleaner to me, but it's not faster.
I would use a pair of arrays or dictionaries (setting them up is left as the proverbial exercise for the reader):
labels[index].Text = "Device " + (index + 1) + " has temperature "
+ temperatures[index].ToString(formatString) + " ℃";
EDIT
From the code in your comment, it seems you want to identify a label by name, and that you will derive the name from an integer variable, like this:
for (int i=1; i<=6; i++)
{
Label label = GetLabelForIndex(i);
//do something with the label here
}
So the question is, how will you get the label for a given index? In other words, what is the implementation of GetLabelForIndex(int)? The answer to that question depends on what kind of Label we're talking about. What library does it come from? Is it WinForms? Silverlight? WPF? If it's WinForms, see Get a Windows Forms control by name in C#. If WPF or Silverlight, see Find WPF control by Name. The accepted answer here also proposes using a dictionary with a string key, which is similar to my suggestion above.
Unless you're doing this thousands of times a second, the performance benefit of using a dictionary is probably insignificant, in which case you should just use Find or FindName directly.