I faced a recent problem, where I was generating the dynamic control on the selection of drop down. When the selection changes, I have to generate another set of dynamic controls, removing the existing controls.
So I was doing following which is not working:
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:
or if you want to remove all controls from a panel for example you could use:
Hope it helps!