2011-12-14 60 views
0

在可视Web部件页上加载事件(c#)我打电话给REST API,它以XML形式返回结果。我想根据返回的结果数量动态设置表格中的标签。作为XML被解析节点1将设置标签1,节点2个标签2等动态导出循环中的标签名称?

在示例代码下面我想在迭代3等迭代2,Label3_1.Text设置迭代1,Label2_1.TextLabel1_1.Text值上。

这是如何实现的?

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; 
} 

回答

1

如果您已将所有标签都作为容器内的控件,则需要在包含控件上使用FindControl方法。

Label toUpdate = (Label)myTable.FindControl("Label1_1"); 
toUpdate.Text = childOne; 

如果标签控件不存在,您将需要创建和动态添加他们(在这种情况下,其ID就是必须是唯一的)。