How to find out if a VB6 control is indexed (control array) in .NET
I working on a VB.NET project to manipulate a VB6 form using COM Interop. Some of the controls on my VB6 form are indexed and some not, so calling ctl.Index fails on those that have no ind开发者_JAVA百科ex. Is there a way to work out if a control is indexed?
I have managed to knife and fork a solution to get this to work. But it isn't that efficient as it iterates through all controls on the form each time. I seem to remember at the back of my mind there is a VB6 function to test whether a control is an array but I can't recall it. My function for anyone who is interested is below but I would still be interested to find a cleaner solution to this if possible?
Private Function FindIndex(ByRef objCtl As Object) As Integer
For Each ctl As Object In objCtl.Parent.Controls
If objCtl.Name = ctl.Name AndAlso Not objCtl.Equals(ctl) Then
'if the object is the same name but is not the same object we can assume it is a control array
Return objCtl.Index
End If
Next
'if we get here then no controls on the form have the same name so can't be a control array
Return 0
End Function
The Following is the VB6 Equivalent if anyone is interested:
Private Function FindIndex(ByRef F As Form, ByRef Ctl As Control) As Integer
Dim ctlTest As Control
For Each ctlTest In F.Controls
If (ctlTest.Name = Ctl.Name) And (Not (ctlTest Is Ctl)) Then
'if the object is the same name but is not the same object we can assume it is a control array
FindIndex = Ctl.Index
Exit Function
End If
Next
'if we get here then no controls on the form have the same name so can't be a control array
FindIndex = 0
End Function
I found a solution similar to that of @Matt Wilko, but it avoids having to loop through all the controls on the form:
Public Function IsControlArray(objCtrl As Object) As Boolean
IsControlArray = Not objCtrl.Parent.Controls(objCtrl.Name) Is objCtrl
End Function
Source : http://www.vbforums.com/showthread.php?536960-RESOLVED-how-can-i-see-if-the-object-is-array-or-not
In vb6 you can use the TypeName function - Control arrays will return type "Object", not the actual control type - like so:
If TypeName(ctrl) = "Object" Then
isControlArray = true
End If
The solutions proposed above do not work if there is only one member of the control array. A simple way to test if a control as a member of a control array is to test for the control's Index Property (Control Array). This Returns the number that uniquely identifies a control in a control array. Available only if the control is part of a control array.
Private Function IsControlArray(Ctl As Control) As Boolean
On Error GoTo NotArray
IsControlArray = IsNumeric(Ctl.Index)
Exit Function
NotArray:
IsControlArray = False
End Function
精彩评论