[英]Removing Controls from asp.net page at runtime
I have an asp.net dashboard site that allows a user to load HTML templates from a dropdownlist. 我有一个asp.net仪表板站点,允许用户从下拉列表中加载HTML模板。 There are multiple types of DevExpress components on the page, including the ASPxDockPanel.
页面上有多种类型的DevExpress组件,包括ASPxDockPanel。 If a user changes templates I get an error that the dockpanel already exists, I would like to include a recursive function like the one below that checks to see if any ASPxDockPanels are present on the page, and if they are present remove them.
如果用户更改模板,则会收到一个错误消息,即该面板已经存在,我想包括一个递归函数,如下所示,该函数检查页面上是否存在ASPxDockPanels,如果存在,请将其删除。 This works for only the first dock panel then bombs out.
这仅适用于第一个扩展坞面板,然后炸毁。 I think this is because an enumerable set of controls cannot be modified while looping through it.
我认为这是因为无法遍历遍历的一组无法枚举的控件。 How can I loop though the controls and remove the dock panels at runtime?
如何在运行时循环浏览控件并删除停靠面板?
protected void LoadTableTemplate(string selectedTemplate, int currentMode)
{
FindAllDockPanels(this);
}
public void FindAllDockPanels(Control ctrl)
{
if (ctrl != null)
{
foreach (Control control in ctrl.Controls)
{
if (control is ASPxDockPanel)
{
ctrl.Controls.Remove(control);
control.Dispose();
}
FindAllDockPanels(control);
}
}
}
Use a temporary collection, like so: 使用临时集合,如下所示:
public void FindAllDockPanels(Control ctrl) {
if (ctrl != null) {
List<Control> remove = new List<Control>();
foreach (Control control in ctrl.Controls) {
if (control is ASPxDockPanel) {
remove.Add( control );
}
}
foreach(Control control in remove) {
control.Controls.Remove( control );
control.Dispose(); // do you really need to dispose of them?
}
FindAllDockPanels(control);
}
}
If you find yourself doing this often, it might be worth moving these "DelayedDelete" actions to an extension method, like so: 如果您发现自己经常这样做,则可能值得将这些“ DelayedDelete”操作移至扩展方法,例如:
public static void DelayedRemove<T>(this IEnumerable<T item> collection, T itemToRemove) {
// add it to a private static dictionary bound to the `collection` instance.
}
public static void DelayedRemoveFinish(this IEnumerable<T item> collection) {
// empty the private static dictionary in here
}
then you'd use it like so: 那么您将像这样使用它:
public void FindAllDockPanels(Control ctrl) {
if (ctrl != null) {
foreach (Control control in ctrl.Controls) {
if (control is ASPxDockPanel) control.Controls.DelayedRemove( control );
}
control.Controls.DelayedRemoveFinish();
FindAllDockPanels(control);
}
}
Much cleaner, no? 清洁得多,不是吗? :)
:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.