How to remove a button in an array using C # .net?

I created up to 20 buttons at runtime.

Now, after the event, I want to remove 15 buttons, leaving the first 5 as they are. How can i do this?

Then, whenever another event is called, the button will be added as before.

+6
c # visual-studio winforms
source share
2 answers

Instead of an array, you should use a list. I think when creating you do something like this:

List<button> buttons = new List<button>(); for( int i = 0; i < 20; i++ ){ Button b = new Button(); ... this.Controls.Add(button); buttons.Add(button); } 

Then, to remove any button from the application, simply do:

 this.Controls.Remove( buttons[i] ); buttons.RemoveAt(i); 

Using this setting, to remove the last 15 buttons, try the following:

 for( int i = 19; i > 4; i-- ){ this.Controls.Remove(buttons[i]); buttons.RemoveAt(i); 

Do not forget that the cycle starts from the 20th element and works down, because if you delete an element inside the list, it means that all elements with a higher index will have an index shifted by 1.

+5
source share

To remove buttons, you must remove it from the control collection.

use this.Contols.Remove( <buttonControl> );

This is similar to how you add buttons at runtime. Instead of .add you use .remove .

0
source share

All Articles