删除动态控件:清除正在运行但不会删除

问题描述 投票:4回答:1

我遇到了一个最近的问题,我在选择下拉菜单时生成动态控制。当选择发生变化时,我必须生成另一组动态控件,删除现有控件。

所以我做了以下无效工作:


    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();
        }


    }

通过此代码,将删除所有控件(动态和静态)。那么应该怎么做呢?

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

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

c# asp.net postback dynamic-controls createchildcontrols
1个回答
1
投票

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

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

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

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

希望能帮助到你!

© www.soinside.com 2019 - 2024. All rights reserved.