0

我有一个类,它在我的网络表单中添加了一些控件。现在我需要通过我的班级访问动态添加的控件。谁能告诉我如何从服务器端代码访问动态添加的控件。

4

2 回答 2

0

如果您已动态添加控件,则您已经拥有对已添加控件的引用;只需保留该参考。

如果由于某种原因无法使用,正如其他人已经建议的那样,FindControl("ID_OF_CONTROL").

但请确保在Id将控件添加到 Controls 集合之前已设置控件的 。:

var tbItem = new TextBox();
tbItem.Id = "tbItem_Id";

// add to some place holder
phLocation.Controls.Add(tbItem); 

您现在可以使用FindControl("tbItem_Id")来引用添加的控件。

如果失败,请确保您掌握了页面和请求的生命周期,您可能会发现在搜索时实际上还没有添加控件。

但我再说一遍,你已经有了参考,把它储存起来并重复使用。

于 2013-07-30T12:06:23.653 回答
0

我找到了问题的解决方案。遍历所有控件。

public static IEnumerable<Control> GetControls(ControlCollection controlCollection)
{
    foreach (Control control in controlCollection)
    {
        yield return control;

        if (control.Controls == null || control.Controls.Count == 0)
            continue;

        foreach (var sub in GetControls(control.Controls))
        {
            yield return sub;
        }
    }
}

创建 IEnumerable 列表后检查控件的 ID。

    foreach (Control c in ctr__)
    {
        if (c.ClientID == "dropUGrp")
        { 
           //Code goes here
           break;
        }
    }
于 2013-07-30T12:52:38.787 回答