To use a variable within your control, you simply declare it as normal (using Dim or Private). If you want it to be accessible by the container (ie the form that your control is placed on), you need to create a property. This is described below.
When you use a control such as the TextBox control, there are a number of properties you can set. Some of them are standard properties that all controls have, such as left, width, tag, and name. Others are unique to the control (and sometimes used by other controls), such as Text, Enabled, Locked and Multiline. To give a control or class a property you can do one of three things (in order of ease):
1) Use the ActiveX Control wizard (click Project|Add User Control|VB ActiveX Control Wizard)
2) Simply declare a public variable, such as:
Public Enabled As Boolean
3) Create a Property Enabled_Let and Property Enabled_Get procedure (see below)
You might decide that therefore you will always use method 1. However, the fastest is not always the best. It is also good experience to understand the workings of properties, rather than letting the VB do it all for you. Though, if you are a complete beginner, then this is probably best.
The second method is also simple, however, this creates a property that can only be set a run time. It also allows the project that uses your control (called the client) to change the value of Enabled without your (the controls) knowledge. If the property requires no validation, and do not need to change any other properties (and therefore you do not care if the client changes it or not), then you might as well just use this method. However, if you need to be notified before a property is changed, or when the client is asking for its value, or you want to change another controls property, or call any other methods ... you need to use the Property statement.
Here is an example:
Dim m_BackColor As Long '// private variable that stores the value of
BackColor.
'// the back color property. This is called when the client requests the value
of BackColor
Public Property Get BackColor() As Long
BackColor = m_BackColor '// return the private variable
End Property
'// this is called when the client requests to change the value of BackColor.
Public Property Let BackColor(ByVal New_BackColor As Long)
'// if the property is read only (ie the client cannot change
its value), you do not need this procedure.
'// before you assign the new value, you could check to see
if it is empty, or a valid colour etc.
m_BackColor = New_BackColor '// set the private variable
to the new value
PropertyChanged "BackColor" '// property
has changed
End Property
Comments