c#asp.net用于将int值附加到标签id

c#asp.net用于将int值附加到标签id,c#,C#,我有以下带有ID的标签: <asp:Label ID="FromName0" runat="server" Visible="true"></asp:Label> <asp:Label ID="FromName1" runat="server" Visible="true"></asp:Label> <asp:Label ID="FromName2" runat="server" Visible="true"></asp:L

我有以下带有ID的标签:

<asp:Label ID="FromName0" runat="server"  Visible="true"></asp:Label>
<asp:Label ID="FromName1" runat="server"  Visible="true"></asp:Label>
<asp:Label ID="FromName2" runat="server"  Visible="true"></asp:Label>
<asp:Label ID="FromName3" runat="server"  Visible="true"></asp:Label>
<asp:Label ID="FromName4" runat="server"  Visible="true"></asp:Label>

我想使用for循环将值分配给标签ID。 我在c#中使用以下标记:

for(int i=0;i
但“查找”显示如下错误: System.Web.UI.ControlCollections没有“查找”的定义。但我已经添加了“System.Web.UI”dll文件。有人能帮我吗

我使用的是dotnetframework4.0

提前感谢。

只需使用:

下面是代码的外观。就像检查控件是否为null会话变量是否为null一样,这可能会给您一个异常

for (int i = 0; i < count; i++)
{
    var label = FindControl("FromName " + i) as Label;

    if(label == null || Session["DeliverAddress" + i] == null)
       continue;

    label.Text = Session["DeliverAddress" + i].ToString();

}
for(int i=0;i
您可以这样做

  public  Control[] FlattenHierachy(Control root)
    {
        List<Control> list = new List<Control>();
        list.Add(root);
        if (root.HasControls())
        {
            foreach (Control control in root.Controls)
            {
                list.AddRange(FlattenHierachy(control));
            }
        }
        return list.ToArray();
    }

这段代码无法编译。在这种情况下,我是什么?他需要开始第二圈。嵌套循环并不有趣!我是你的自定义变量..删除它..给出一个自定义名称,但他有他循环的控件计数->他不能写整个控件名。他需要用你的代码添加第二个循环。如果您想找到一个控件,它将起作用,但这不是这里的目标。您可以在单独的方法中移动代码,在该方法中,您将使用controlName作为参数。您应该从1循环到count,并为方法指定正确的名称。这将满足op要求。如果需要,请添加更多。
for (int i = 0; i < count; i++)
{
    var label = FindControl("FromName " + i) as Label;

    if(label == null || Session["DeliverAddress" + i] == null)
       continue;

    label.Text = Session["DeliverAddress" + i].ToString();

}
  public  Control[] FlattenHierachy(Control root)
    {
        List<Control> list = new List<Control>();
        list.Add(root);
        if (root.HasControls())
        {
            foreach (Control control in root.Controls)
            {
                list.AddRange(FlattenHierachy(control));
            }
        }
        return list.ToArray();
    }
protected void Page_Load(object sender, EventArgs e)
    {
        Control[] allControls = FlattenHierachy(Page);
        foreach (Control control in allControls)
        {
            Label lbl = control as Label;
            if (lbl != null && lbl.ID == "FromName0")
            {
                lbl.ID = "myid";//Do your like stuff
            }
        }
    }