4

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...

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 に答える