The DatagridviewCell.Datagridview property is read-only. Same applies for other datagridview elements with a Datagridview reference, like rows and columns. Yet somehow when you add/remove elements from a datagridview, this property is set properly behind the scenes, so there is never any inconsistency between the parent datagridview’s references to its elements, and vice versa.
How is datagridview accomplishing this? I’m trying to do something similar myself. The only “trick” that I know of is to put the collection definition inside the class definition or vice versa, so that the element or collection has access to other’s private fields, but looking at the datagridview namespaces this does not appear to be the case.
The DateGridView is using the “internal” access modifier. As you may know, there are 4 different access modifiers.
Here’s a quick summary of the behaviour of the access modifiers:
public: MyPetPeeve is accesible to anyone who wants to know.
private: MyPetPeeve is only accessible from within the class or struct that contains it.
protected: MyPetPeeve is accessible to the class or struct that contains it. PLUS, any class derived from MyPetPeeves containing class.
internal: MyPetPeeve is accessible to any class or struct that exists in the same assembly. For example, the DataGridView exists in the System.Windows.Forms assembly, so any class or struct found in System.Windows.Forms can change DatagridviewCell.Datagridview property. To anyone else outside System.Windows.Forms, in this case: you, it appears to be private.