ASP循环中的标签进程列表

时间:2011-08-25 07:12:56

标签: asp.net

我有一张桌子上有几个标签lbl1,lbl2 ....,lbl6 ......连续编号

我想使用索引在for循环中访问它们。这是我的puedocode

//PuedoCode:
int _NUMCOUNT = 6;
string labelname;
string[] strArray = new string[_NUMCOUNT];
//Store some values in strArray

for (int i=0; i<_NUMCOUNT; i++)
{
     labelname = "lbl" + (i + 1).ToString();
     labelname.Text = strArray[i]
 }

可以这样做吗?我不想使用占位符&amp;将标签添加到其中。我已经在格式化的表格中有标签。

5 个答案:

答案 0 :(得分:2)

使用FindControl方法,

//PuedoCode:
int _NUMCOUNT = 6;
string labelname;
string[] strArray = new string[_NUMCOUNT];
//Store some values in strArray

for (int i=0; i<_NUMCOUNT; i++)
{
   Label control=(Label)tab.FindControl("lbl"+i);  //Assume that the "tab" is container (table) control.
   if(control!=null)
       control.Text = strArray[i];
 }

答案 1 :(得分:1)

使用Control.FindControl Method

  

使用以下命令在当前命名容器中搜索服务器控件   指定的id参数。

Label label = FindControl("lbl" + i.ToString()) as Label;

答案 2 :(得分:0)

int _NUMCOUNT = 6;
        string labelname;
        string[] strArray = new string[_NUMCOUNT];
        //Store some values in strArray

        for (int i = 0; i < _NUMCOUNT; i++)
        {
            Label lbl = (Label)yourTable.FindControl(String.Format("lbl{1}", i + 1)); //yourTable is the id of table that contains labels
            if (lbl != null)
            {
                lbl.Text = strArray[i];
            }
        }

答案 3 :(得分:0)

你不应该这样做。只需将标签放在某种容器中(例如Panel或Placeholder),然后执行以下操作:

<asp:Panel ID="Panel1" runat="server">
    <asp:Label ID="Label1" runat="server" />
    <asp:Label ID="Label2" runat="server" />
    <asp:Label ID="Label3" runat="server" />
</asp:Panel>

在您的代码中:

foreach (Label label in Panel1.Controls.OfType<Label>())
{
    label.Text = "Something";
}

答案 4 :(得分:0)

感谢您的回复。它指出了我正确的方向。

我必须将代码修改为

ContentPlaceHolder myContent = (ContentPlaceHolder)this.Master.FindControl("ContentPlaceHolder1"); //ASP page has master & this is the content page
string lblName = "lbl" + (i + 1).ToString();
Label lblControl = myContent.FindControl(lblName) as Label;