I've created upto 20 buttons in runtime.
Now upon an event, I want to remove 15 buttons leaving first 5 as it is. How can I do so?
Then whenever another event is called same button will be added as before.
Instead of array, you should use a list. I guess 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 app again, simply do:
this.Controls.Remove( buttons[i] );
buttons.RemoveAt(i);
With this set up, to remove the last 15 buttons, try the following:
for( int i = 19; i > 4; i-- ){
this.Controls.Remove(buttons[i]);
buttons.RemoveAt(i);
Remember to let the loop start at the 20th item, and work downwards, because if you delete an element inside a list, that means that all the elements with a higher index will get their index shifted by 1.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With