On a Visual Web Part pageLoad event (c#) I am calling a REST API which returns results in XML. I want to dynamically set labels in a table depending on the number of results returned. As the XML is parsed node 1 will set labels 1, node 2 labels 2 etc.
In the example code below I want to set the value of Label1_1.Text on iteration 1, Label2_1.Text on iteration 2, Label3_1.Text on iteration 3 and so on.
How can this be achieved?
foreach (XmlNode elem in nodes)
{
string childOne = elem["contact1"].InnerText.ToString();
string childTwo = elem["contact2"].InnerText.ToString();
string childThree = elem["contact3"].InnerText.ToString();
string childFour = elem["contact4"].InnerText.ToString();
// I want Label1 to effectively be Labelx (x being the iteration)
// so it is dynamic based on the number of iterations in the loop
Label1_1.Text = childOne;
Label1_2.Text = childTwo;
Label1_3.Text = childThree;
Label1_4.Text = childFour;
}
You will need to use the FindControl method on the containing control if you already have all of the labels as controls within the container.
If the label controls don’t already exist you will need to create and add them dynamically (in which case the Id would be need to be unique).