프로그램(C# etc.)

자식 폼을 전부 삭제하는 코드

질문폭격 2023. 3. 2. 13:51

 

 이 코드는 LINQ의 OfType 메서드를 사용하여 Controls 컬렉션을 필터링하고 Form2를 입력합니다. 그런 다음 Any 메서드를 사용하여 컬렉션에 남아 있는 자식 양식이 있는지 확인합니다. 있는 경우 First 메서드를 사용하여 첫 번째 자식 폼을 찾아 Controls 컬렉션에서 제거하고 폐기합니다.

 

 이 메서드는 좀 더 간결하고 제거할 별도의 하위 양식 목록을 생성할 필요가 없지만 여전히 Controls 컬렉션을 여러 번 반복하므로 컬렉션이 매우 큰 경우 속도가 느려질 수 있습니다. 성능이 중요한 경우 앞서 설명한 2루프 방법을 사용하는 것이 더 나을 수 있습니다.

            // Loop through all child forms in the parent form's Controls collection
            while (this.Controls.OfType<Form2>().Any())
            {
                // Find the first child form in the Controls collection
                Form2 childForm = this.Controls.OfType<Form2>().First();

                // Remove the child form from the parent form's Controls collection
                this.Controls.Remove(childForm);

                // Dispose the child form to release its resources
                childForm.Dispose();
            }