获取动态添加控件的ID

时间:2010-01-29 05:43:21

标签: asp.net

我有一个html表“table”并在运行时添加控件:

HtmlTableRow tabelrow = new HtmlTableRow();

HtmlTableCell tablecell = new HtmlTableCell();

Label lbl = new Label();

tablecell.Controls.Add(lbl);

然后我想通过使用foreach来获取每个控件

,例如(foreach control c in table.controls)(foreach control c in tablecell.controls) 但它不起作用。

1 个答案:

答案 0 :(得分:1)

尝试以下方法。我可以使用ID获取控件,但您需要先为其分配ID。

HtmlTable table = new HtmlTable();

   for (int i = 0; i < 10; i++)
   {
      HtmlTableRow tablerow = new HtmlTableRow();
      tablerow.ID = Guid.NewGuid().ToString();

      HtmlTableCell tablecell = new HtmlTableCell();
      tablecell.ID = Guid.NewGuid().ToString();

      Label lbl = new Label();
      lbl.ID = Guid.NewGuid().ToString();

      tablecell.Controls.Add(lbl);
      tablerow.Controls.Add(tablecell);
      table.Controls.Add(tablerow);
   }

   List<string>RowID = new List<string>();
   List<string>CellID = new List<string>();
   List<string>LabelID = new List<string>();

   foreach (Control Row in table.Controls)
   {
      //Each control will be a tablerow.
      RowID.Add(Row.ID);

      CellID.Add(Row.Controls[0].ID);

      LabelID.Add(Row.Controls[0].Controls[0].ID);
   }

你到底想要做什么?请详细说明。