我最近遇到了一个问题,我在下拉菜单的选择上生成动态控件。当选择更改时,我必须生成另一组动态控件,删除现有控件。
所以我在做以下不起作用的事情:
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();
}
}
But the similar code with Clear() method is working fine. So what shall I do about it?
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();
}
}
By this code, all the controls(both dynamic and static) are removed. So what shall be done about it?
Please let me know if I am doing something wrong.
I am calling this method on dropdown selection change event firing. These controls are added to the table...
If you know your control's names you could use this:
foreach(Control control in Controls){
if(control.Name == "yourControlName"){
Controls.Remove(control);
}
}
或者,如果要从面板中删除所有控件,例如,可以使用:
foreach(Control control in panel.Controls){
panel.Controls.Remove(control);
}
希望对您有所帮助!