Search code examples
vb.netclasstypesuser-controlsencapsulation

Private Child Type with Access to Parent Properties


I'm trying to create a control (Parent Class) that uses a custom grid (Child Class). The grid has a series of constructors and methods for populating itself based on property values in the [parent] control.

The only way I found to make these property values available to the grid is by making them Shared but that's causing me all kinds of issues.

REQUIREMENTS

  • Properties in the control (parent) must be accessible to the grid (child).
  • Properties in the control must be visible in the design-time properties explorer.
  • The grid class must only be instantiable by the parent class.

As a side note: please indicate if your answer will allow me to share properties/methods back and forth between child and parent. That would be nice, but just a bonus.

Thanks ;)

EDIT - A VERY simple example based on my situation:

Partial Public Class catContent
    Inherits System.Web.UI.UserControl

    Protected Sub Page_Load(sender, e) Handles Me.Load
        Page.Controls.Add(New CategoryResultGrid(category))
    End Sub

    Private Shared _product As String = String.Empty

    Shared Property Product() As String
        Get
            Return _product
        End Get
        Set(ByVal value As String)
            _product = value.Trim()
        End Set
    End Property

    Private Class CategoryResultGrid
        Inherits GridView

        Sub New(ByVal category As String)
            'How do I access "Product" here without sharing it?
        End Sub
    End Class
End Class

Solution

  • Do NOT use shared, it will break your app as soon as you put more than one of you custom control in your app.

    If you only want the Grid to exist in the context of the Parent control, then consider exposing it similar to how the ListView control exposes its Items collection.

    If you want your Grid to access fields in the (parent) Control there are several ways to do that. You could pass an instance of the Parent to the Grid, you can let the Grid use the standard Control methods to get its parent reference, or you can implement the Grid as an inner class of the Parent.