【问题标题】:Adding Controls to Control Collection from an update panel从更新面板将控件添加到控件集合
【发布时间】:2013-03-21 21:23:09
【问题描述】:

按照这两个线程: How can I create an Array of Controls in C#.NET? Cannot Access the Controls inside an UpdatePanel

我现在有这个:

ControlCollection[] currentControlsInUpdatePanel = new ControlCollection[upForm.Controls.Count];
foreach (Control ctl in ((UpdatePanel)upForm).ContentTemplateContainer.Controls)
{
    currentControlsInUpdatePanel.
}

currentControlsInUpdatePanel 没有添加或插入方法。为什么我发布的第一个链接允许该用户 .add 到他的收藏中。这就是我想做的,在我的 upForm 更新面板中找到所有控件。但我不知道如何将它添加到我的控件集合中。

【问题讨论】:

    标签: asp.net user-controls updatepanel controlcollection


    【解决方案1】:

    我认为这段代码没有意义。您正在创建一个 ControlCollection 对象数组并尝试在其中存储 Control 对象。此外,由于 currentControlsInUpdatePanel 对象是一个数组,因此该对象上没有可用的 Add() 方法。

    如果您想使用 Add() 方法,请尝试将 currentControlsInUpdatePanel 创建为 List 对象。

    例子:

    List<Control> currentControlsInUpdatePanel = new List<Control>();
    foreach(Control ctl in ((UpdatePanel)upForm).ContentTemplateContainer.Controls)
    {
        currentControlsInUpdatePanel.Add(ctl);
    }
    

    如果您想继续使用数组来存储 Control 对象,则需要使用索引值来设置数组中的对象。

    例子:

    Control[] currentControlsInUpdatePanel = new Control[((UpdatePanel)upForm).ContentTemplateContainer.Controls.Count];
    for(int i = 0; i < upForm.Controls.Count; i++)
    {
        currentControlsInUpdatePanel[i] = ((UpdatePanel)upForm).ContentTemplateContainer.Controls[i];
    }
    

    【讨论】:

      【解决方案2】:

      UpdatePanel 的子控件集合是一个特殊的集合,它只包含一个子控件:它的模板容器。那么那个控件包含UpdatePanel的所有子控件(例如GridViewButton)。

      正如在问题中链接的其他问题中指出的那样,递归地遍历子控制树是最好的方法。然后,当您找到需要添加控件的位置后,请在该位置致电Controls.Add()

      我的建议是另一种方法:在UpdatePanel 中放置一个&lt;asp:PlaceHolder&gt; 控件并为其命名并为其添加控件。访问UpdatePanel 本身的控件集合应该没有特别的优势,然后您就不必深入研究控件的实现细节(虽然它们不太可能改变,但会使代码更难阅读)。

      【讨论】:

        【解决方案3】:

        尝试使用

        ControlCollection collection = ((UpdatePanel)upForm).ContentTemplateContainer.Controls;
        

        这为您提供了该控件集合中的所有控件。从那里您可以使用 CopyTo 将其复制到您需要的数组中:

        Control[] controls = new Control[collection.Length];
        collection.CopyTo(controls , 0);
        

        【讨论】:

          猜你喜欢
          • 2023-03-31
          • 2011-06-25
          • 2019-10-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-08-25
          • 2012-02-25
          • 1970-01-01
          相关资源
          最近更新 更多