4

我最近遇到了一个问题,我正在生成对下拉选择的动态控制。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();
        }


    }

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

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

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

4

1 回答 1

1

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

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

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

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

希望能帮助到你!

于 2012-06-14T14:36:50.703 回答