6

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.

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

0

For removing buttons, you have to remove it from the controls collection.

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.