在Loop中动态导出标签名称?

时间:2011-12-14 14:58:00

标签: c# visual-studio-2010 sharepoint-2010

在Visual Web Part页面上载荷事件(c#)我正在调用一个以XML格式返回结果的REST API。我想根据返回的结果数在表中动态设置标签。在解析XML时,节点1将设置标签1,节点2标记2等。

在下面的示例代码中,我想在迭代1上设置Label1_1.Text的值,在迭代2设置Label2_1.Text,在迭代3设置Label3_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 个答案:

答案 0 :(得分:1)

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

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

如果标签控件尚不存在,则需要动态创建和添加它们(在这种情况下,Id必须是唯一的)。