H
H
h1_0ne2020-03-14 14:59:21
C++ / C#
h1_0ne, 2020-03-14 14:59:21

Why don't collection events work if the UserControl that owns this collection is a field and not a local variable?

Good afternoon. I have a collection of controls inherited from IList. In the Add method, I call the ReportAdded event

spoiler

internal class ReportList : IList<PreviewReport>
    {
     ...
    public readonly List<PreviewReport> Items;
public ReportList()
        {
            Items = new List<PreviewReport>();
        }

        public void Add(PreviewReport previewReport)
        {
            Items.Add(previewReport);
            ReportAdded?.Invoke(previewReport, new EventArgs());
        }
     ....

    }



There is also a UserControl Folder that contains this collection. The idea is that when an element is added to the collection, it will be added to the Controls of the current Folder. To do this, in the Folder constructor, I subscribe to the ReportAdded collection event

spoiler


public Folder()
        {
            InitializeComponent();
            Reports = new ReportList();

            Reports.ReportAdded += Reports_ReportAdded;
        }



I also have a handler for this event, which, according to certain logic, should add an element from Reports to the controls of the current Folder

spoiler


private void Reports_ReportAdded(object sender, EventArgs e)
        {
            //логика
        }



Then, in the form constructor, I add elements to the Folder collection.

spoiler


for (int i = 0; i < 8; i++)
                folder1.Reports.Add(new PreviewReport());



The problem is that if the Folder object is created in some method and is a local variable, the event will fire. If the Folder object is a field, then this event will be null, although the section of code where the event subscription is performed passes.

Folder is a field

Subscribed to the event
5e6cc561dc8ae823043335.png

Add elements
5e6cc5ba2e234995142208.png

null event
5e6cc5ef7ab6e690572113.png


Folder is a local variable

Создаю объект
5e6cc6b6513d9934523779.png

происходит подписка на событие
5e6cc561dc8ae823043335.png

событие отрабатывает
5e6cc6f1072d8130991392.png


Why is this happening and how to make it so that the event is processed regardless of whether Folder is a field or a local variable?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question