Name It Right


I flamed about the hated XEditor1 convention in Chapter 1. Well, the buck stops here. The only way I’m ever going to succeed in my campaign against evil is to stop making it so damn easy. If you want to name an instance of my control XEditor1, you’re going to have to type it in yourself. I define the preferred prefix name as edit. For the first XEditor control you place on a form, I give you the name edit. Normally, you’ll need only one XEditor per project, but if you’re going to have more than one, you’ll probably want to rename it to editRight, editTop, or something similar. In the unlikely case that you fail to rename your first XEditor and then request a second, its name will come out as edit1.


The code that makes this work starts when the control is created in the User­Control_InitProperties event:

Extender.Name = UniqueControlName("edit", Extender)

The UniqueControlName function creates a unique name for the current instance, based on the given prefix. The code resides in CTLTOOL.BAS, a module for tools that are related to creating controls:

Function UniqueControlName(sPrefix As String, Ext As Object) As String
Dim v As Variant, s As String, c As Long, fFound As Boolean
On Error GoTo UniqueControlNameFail
s = sPrefix
Do
fFound = False
' Search for a control with the proposed prefix name
For Each v In Ext.Container.Controls
If v.Name = s Then
' Nope, try another name
fFound = True
c = c + 1
s = sPrefix & c
Exit For
End If
Next
Loop Until fFound = False
' Use this name
UniqueControlName = s
Exit Function

UniqueControlNameFail:
' Failure probably means no Extender.Container.Controls
UniqueControlName = sPrefix
End Function

Visual Basic designers would probably be horrified at the use I’ve put to the Extender object. This isn’t what it was designed for. But I could have done worse.


You can get around my naming convention enforcement by copying an existing XEditor control and pasting it onto the form. Visual Basic will ask if you want a control array, and if you say no, it will give you the hated name XEditor1. I tried to intercept and rename the control in this situation and, after much experimenting, I found a way. But my fix had a side effect. If a user deliberately typed XEditor1 as the instance name, I would change the name to edit1 the next time the form was loaded. Even I am not rude enough to leave code like that in my control.