【问题标题】:Get list of all controls in webform [duplicate]获取网络表单中所有控件的列表[重复]
【发布时间】:2014-01-06 16:22:27
【问题描述】:

我有一个网络表单,想运行一个方法来从表单中返回所有控件 ID 的列表,这样我就可以将列表导出到 Excel 之类的地方(从另一个对象复制和粘贴就可以了)。

这是我要返回的示例:

lblName
lblAddress
txtEmail
ddlSelection

我该怎么做?

【问题讨论】:

  • 请搜索 SO,因为这个问题被问了很多次。
  • @connersz,试试这个链接:stackoverflow.com/questions/277646/…
  • 我看过这个例子,但我不想对另一个控件中的某些控件做特别的事情。我实际上想将网络表单中的每个控件都列出来。
  • 该链接问题上the accepted answer 中的第一个sn-p 获取页面控件层次结构中的每个控件。您需要做的就是遍历返回对象中的值并以某种方式将它们显示在您的页面上(在转发器中,为每个对象执行“Response.Write”,将所有控件 ID 连接成一个巨大的字符串并将它们放入标签等)。
  • cmd.prompt 这里的递归解决方案可能比 Cristian Libardo 的 yield-return 解决方案更容易理解(尽管后者肯定更优雅)

标签: c# asp.net webforms


【解决方案1】:
// Create a method to loop through
// the control tree and record ids
public void GetAllControlIDs(Control c, List<String> ids)
{
    ids.Add(c.ID);
    if(c.HasControls())
        foreach(Control ch in c.Controls)
            GetAllControlIDs(ch, ids);
}

// Call your method and pass in the
// Form since your question asks for
// the Form controls
List<String> allControlIDs = new List<String>();
GetAllControlIDs(this.Page.Form, allControlIDs);

foreach (String id in allControlIDs)
    Console.WriteLine(id);

【讨论】:

    猜你喜欢
    • 2017-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-16
    • 1970-01-01
    • 2010-09-11
    • 1970-01-01
    • 2017-01-21
    相关资源
    最近更新 更多