C# Pictureboxen löschen?

  • C#
  • .NET (FX) 4.5–4.8

Es gibt 6 Antworten in diesem Thema. Der letzte Beitrag () ist von nafets.

    C# Pictureboxen löschen?

    Hallo,

    ich erstelle in einer Methode die in Form1_Load aufgerufen wird Pictureboxen, und füge diese zu den this.Controls hinzu.
    Nun dachte ich dass wenn ich diese Funktion aufrufe alle wieder gelöscht werden:

    C#-Quellcode

    1. public void DeletePics()
    2. {
    3. foreach (PictureBox p in this.Controls)
    4. {
    5. this.Controls.Remove(p);
    6. p.Dispose();
    7. }
    8. }


    Doch es werden nur alle 2 Reihen gelöscht, etwa so:

    P = Picturebox
    X = Gelöschte Picturebox

    Vor dem Aufruf:

    PPPPPPPPPP
    PPPPPPPPPP
    PPPPPPPPPP
    PPPPPPPPPP
    PPPPPPPPPP
    PPPPPPPPPP

    Nach dem Aufruf:

    PPPPPPPPPP
    XXXXXXXXXX
    PPPPPPPPPP
    XXXXXXXXXX
    PPPPPPPPPP
    XXXXXXXXXX

    Ich verstehe dass nicht ganz!

    Grüße,
    DragonSlayerMarc
    There are only 10 types of people in the world: Those who understand binary and those who don't.
    Liegt vermutlich daran, dass nach dem Entfernen die restlichen Controls von this.Controls in der Liste einrücken, da ja ein Element entfernt wurde.
    Du löschst zB. zuerst das 1. Control am Index 0, dann werden alle einen Index zurückgerückt (2. Control liegt nun am Index 0, 3. Control am Index 1 etc.) und wenn dann am Index 1 gelöscht werden soll, liegt dort aber schon Control 3 und 2 wird ausgelassen.

    Lösung: nicht mit foreach durchlaufen, sondern mit einer Zählschleife, aber nicht von vorne nach hinten, sondern von hinten nach vorne, denn wenn du das letzte Control entfernst, bleibt die Reihenfolge der restlichen Controls bestehen.
    @Counterbug funktioniert :)
    Funktioniert aber auch wenn ich die Funktion 2x aufrufe?
    Ist ja egal denn jetzt klappt es.

    Vielen Dank
    Gruß,
    DragonSlayerMarc
    There are only 10 types of people in the world: Those who understand binary and those who don't.