I would do it like this (i use vb.net)
Class MyUserControlA
'Inherits UserControl '(This line will be in your desinger file)
Delegate Sub SomethingEventHandler (sender as object, e as EventArgs) '(assumes you are not going to override event args)
Public Event SomethingEvent as SomethingEventHandler
private _someData as String
Public Readonly Property MyDataGrid as DataGridView
Get
Return DataGridView1 ' this is in the designer form of the user control
End Get
Public Property SomeData as string
Get
return _someData
End Get
Set(value as string)
_someData as string
End Set
End Property
Protected Sub OnSomethingEvent()
RaiseEvent SomethingEvent(Me, EventArgs())
End Sub
'....something happens and you want to raise the event
OnSomethingEvent
End Class
Implement the main form as follows
Class MainForm
Implements Form 'designer file
'....other code
Sub MyUserControlA1_SomethingEvent Handles MyUserControlA1.SomethingEvent
'instead of calling a property you could override eventArgs and return the control that way.
MyUserControlB1.OtherDataGridView=MyUserControlA1.MyDataGrid
End Sub
End Class
UserControlB is as follows:
Class UserControlB
Inherits UserControl ' designer form
'...other code
private _dataGrid as DataGridView=Nothing
Public Property DataGrid() As DataGridView
Get
Return _dataGrid
End Get
Set(ByVal value As DataGridView)
'only set if null
if _dataGrid is Nothing then _dataGrid = value
End Set
End Property
'do stuff with the control...I would always check for null
function DoSomethingWithDataGrid as integer
if _dataGrid IsNot Nothing then
return _dataGrid.Items.Count
End If
End Sub
End Class
THIS CODE IS NOT TESTED.
This is fairly loosely coupled this way. I guess in an ideal world you would wrap what you need in UserControlA DataGrid in methods and properties and consume them that way. But if there is a lot of members you are referecning in the DataGrid then this is certainly easier.
I am not professing that this is a perfect design. I am still learning winforms architecture. What do you experts think?
Seth B Spearman