Today I had an issue, trying to discover which report/form a given control belongs to. I needed to know this for some other code I am using.
At first I thought it would be so simple. Just use the .Parent property of the control.
More problems
However I soon realised that the .Parent does not always refer to the form/report. For a label for instance it refers to the Control to which the label is attached, and for a control such a textbox or combobox placed inside a tabcontrol the .Parent property refers to the page on which the control resides, and the pages .Parent property is actually the tab control So in some cases to get the form/report you might need to go through several objects to actually get the form/report.
Solution
So I wrote this short bit of code, which will go recursively check the parent of the control, until it finds a Form or Report object, and then return that.
Expand|Select|Wrap|Line Numbers
- Public Function GetControlParentObject(ctl As Control) As Object
- '---------------------------------------------------------------
- '---------------------------------------------------------------
- ' Procedure : GetControlParentObject
- ' Author : AEC - Anders Ebro Christensen / TheSmileyCoder
- ' Date : 2013-04-12
- ' Version : 1.0
- ' Purpose : Return the Form or report to which a control of any type belongs.
- '---------------------------------------------------------------
- '---------------------------------------------------------------
- If (TypeOf ctl.Parent Is Form Or TypeOf ctl.Parent Is Report) Then
- Set GetControlParentObject = ctl.Parent
- Else
- 'Call self recursively on parent object
- Set GetControlParentObject = GetControlParentObject(ctl.Parent)
- End If
- End Function
Feedback, comments and discussions are always welcome.
If you did find this useful and want to see more like it, please take the time to drop a comment here.
Remember comments and feedback are the fuel that keeps the fire going.