Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 612
saaZ Avatar asked Feb 14 '11 09:02

saaZ


1 Answers

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.

like image 105
Øyvind Bråthen Avatar answered Sep 30 '22 20:09

Øyvind Bråthen