c# - 删除动态控件 : Clear is working but not remove

标签 c# asp.net postback dynamic-controls createchildcontrols

我最近遇到了一个问题,我在选择下拉菜单时生成动态控件。 When the selection changes, I have to generate another set of dynamic controls, removing the existing controls.

所以我做了以下不起作用的事情:


    private void ClearDynamicControls()
    {
        if (adapter != null)
        {
            //This has all the controls saved in some dictionary, key as control ID
            var controls = adapter.GetAllControls().Keys;
            Control mainControl = (PlaceHolder)this.Form.FindControl("MainContent");

            foreach (String controlName in controls)
            {
                Control controlToRemove = this.Form.FindControl("MainContent").FindControl(controlName);
                mainControl.Controls.Remove(controlToRemove);

            }
            var controls2 = mainControl.Controls;
            //clearing the controls in the dictionary
            adapter.ClearAllControls();
        }


    }

但是使用 Clear() 方法的类似代码工作正常。那我该怎么办呢?


    private void ClearDynamicControls()
    {
        if (adapter != null)
        {
            //This has all the controls saved in some dictionary, key as control ID
            var controls = adapter.GetAllControls().Keys;
            Control mainControl = (PlaceHolder)this.Form.FindControl("MainContent");
            mainControl.Controls.Clear();


            //clearing the controls in the dictionary
            adapter.ClearAllControls();
        }


    }

通过这段代码,所有的控件(包括动态和静态的)都被删除了。那么应该怎么办呢?

如果我做错了什么,请告诉我。

我在触发下拉选择更改事件时调用此方法。这些控件被添加到表中...

最佳答案

如果您知道控件的名称,您可以使用这个:

foreach(Control control in Controls){
  if(control.Name == "yourControlName"){
    Controls.Remove(control);
  }
}

或者如果您想从面板中删除所有控件,例如您可以使用:

foreach(Control control in panel.Controls){      
        panel.Controls.Remove(control);
    }

希望对您有所帮助!

关于c# - 删除动态控件 : Clear is working but not remove,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11035251/

相关文章:

c# - “T”不包含定义

java - 在 Selenium WebDriver 中使用特定语言有好处吗?

c# - 没有ajaxtoolkit的asp.net下拉列表ajax调用

javascript - 无法从服务器端读取隐藏字段值

c# - 如何在异步回发期间重定向浏览器?

.net - 使用 Javascript .NET 回发传递多个参数

c# - 服务器无法在发送 HTTP header 后附加 header

c# - 使用 Quartz 每天随机触发一个函数

c# - 转换RGB方法?

c# - Repeater 中的 LinkBut​​ton 会导致回发,而按钮则不会