Monday, May 29, 2000

Programming Tips & Tricks #0003---Changing Control names in VB6

Tips & Tricks #0003

Have you ever wished you had named a Visual Basic control by another name—or come across a project where the original programmer accepted all of the default control names—such as Command1, List1, Text1, etc.

Changing the name of a control is easy---you just need to open up the Properties Window for that control and change the Name property. However, what happens to the code associated with that control won’t make you happy!

The code seems to disappear---in actuality, any event procedure associated with the originally named control is relegated to the General Declarations Section of the form. As a result, when you run your program, that code is never executed.

So how do you “get the code back”?

The code hasn’t really gone away---all you need to do is find the event procedure in the General Declarations Section of the form—and then change the “control name” portion of the Procedure header to the new name of the control.

For instance, if you had this code in the Click Event procedure of a Command Button named Command1…

Private Sub Command1_Click()

Msgbox “I love VB”

End Sub

and then renamed the control to cmdOK---VB ‘moves’ this code to the General Declarations Section of the Form.

All you need to do is modify the procedure so that it looks like this…

Private Sub cmdOK_Click()

Msgbox “I love VB”

End Sub

Now, VB will once again associate this code with the command button---and when you run your program, the code will execute---just like before.

By the way, some of my fellow programmers rename their event procedures prior to changing the name of the control. Either way, the effect is still the same---the code will be associated with the newly named control.

No comments: