我最近遇到了一个问题,我在选择下拉菜单时生成动态控件。 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/