I have at my disposal:

  • The main form that contains the DataGridView.
  • Additional form where I enter the data of the object being created
  • Class library

On the main form there is a button "AddObjectButton", clicking on which opens an additional form. In an additional form, after entering data about an object, clicking on the "Add object" button invokes the object constructor described in the class library. This object is added to the collection (List <>), which is a static member of the Home Form class. After that, the data entry form closes.

Task: with the appearance of new objects in the collection, to display their presence in the DataGridView. If I understand correctly, then you can create an event that will respond to the creation of the object and call the method of displaying this object in the DataGridView.

Tell me how to implement it.

    1 answer 1

    You should create your class inherited from List, then add an event to it.

    It is done like this:

    class MyList<T> : List<T> { public event EventHandler OnAdd; public void Add(T item) { if (null != OnAdd) { OnAdd(this, null); } base.Add(item); } } 

    Then you hang the handler in the form:

     static void Main(string[] args) { MyList<int> l = new MyList<int>(); l.OnAdd += new EventHandler(l_OnAdd); l.Add(1); } 

    Created by SO .

    • Thank you, I understand) - Archie
    • five
      And why not ObservableCollection? The problem with this List extension is that the Add method in the base class is non-virtual. - VladD