Archive for the ‘Visual-Basic’ Category

Visual Basic Connection to MySQL

Sunday, January 17th, 2010

I want to use MySQL with Visual Basic in an effort to bypass the difficulties encountered when trying to use the Microsoft database tools.  Those problems include chronic difficulties getting my distribution packages to work on customer computers.

 

Download zip archive of vb project that connects to MySQL database

Making a Visual Basic Installation package including MySQL

Visual Basic 6 – Microsoft mdb simple database functions

Saturday, November 7th, 2009

Searching on: sql for access

VB Visual Basic ModBus Checksum Routine

Sunday, October 12th, 2008

Function CRC16_BIN(ByRef ModBus_Data() As Long, NumBytes As Integer) As Long
  
    Dim Temp As Long
    Dim CRC As Long
    Dim Polynomial As Long
    Dim i As Integer
    Dim j As Integer
‘—– following are read sequence checksum verification vectors  — test where either hi or lo byte == 0
‘— Example temperature= 1 :   1  3  64  0  1  217  144
‘—         temperature=255:   1  3  64  0  255  88  16
‘—         temperature=256:   1  3  64  1  0  25  192
‘—         temperature=257:   1  3  64  1  1  216  0
‘—                     =0 :   1  3  64  0  0  24  80
  ‘— verified write string = Chr(1) & Chr(6) & Chr(64) & Chr(3) & Chr(232) & Chr(24) & Chr(34)
    CRC = 65535          ‘–bottom 16 bits are all 1’s
    Polynomial = 40961   ‘–poly = A001
    For i = 0 To NumBytes – 1
      CRC = CRC Xor ModBus_Data(i)
      For j = 0 To 7
        If (CRC And 1) Then
          CRC = (ShiftRight(CRC) Xor 40961)
        Else
          CRC = ShiftRight(CRC)
        End If
      Next j
    Next i
    CRC16_BIN = CRC And 65535
   
    End Function

ZedGraph is a powerful alternative to Visual Basic MSChart

Saturday, October 11th, 2008

The wiki for ZedGraph.

Visual Basic: Returning an array from a function

Friday, October 3rd, 2008

 

How to return an array from a function

Parent Form Function that passes back an Array / Vector

 Private Sub ReceiveArray_Click()
    Dim intRcvArray() As Integer
    Dim i As Integer

    UserInterface.Text = ""
    intRcvArray = NumberList()                   ‘ —Get the array of strings.
   
    For i = LBound(intRcvArray) To UBound(intRcvArray)     ‘ —Display the strings.
       UserInterface.Text = UserInterface.Text & CStr(i) & " "
    Next i

End Sub

Private Function NumberList() As Integer()          ‘ — This function returns an array 
  Dim intArray() As Integer
  Dim i As Integer

    ReDim intArray(1 To 10)
    For i = 1 To 10
        intArray(i) = i             
    Next i

    NumberList = intArray
End Function

 

Code here: ReturnArray.zip

Visual Basic: How to pass an array parameter to another routine

Thursday, October 2nd, 2008
This routine will pass a parameter to another routine This routine receives the call with array as parameter

 

Sub TestPassArray()

  Dim LongArray(1 To 5) As Long
  Dim i As Integer
 
  For i = 1 To 5
    LongArray(i) = i
  Next i
  
  UserDisplay.Text = CStr(PassTest(LongArray()))

End Sub                                                                                                      

 

Function PassTest(ByRef LongPass() As Long) As Long

  Dim i  As Integer
  Dim Sum As Long
 
  For i = 1 To 5
     Sum = Sum + LongPass(i)
  Next i
 
PassTest = Sum
  
End Function

 

 

 

  1. The passing routine packs   1,2,3,4,5 into an array.
  2. The called routine calculates the sum of all the values in the array and passes the result back to the calling routine.

Visual Basic: Saving Custom Control Persistant Properties

Thursday, October 2nd, 2008

For more on this subject Google Search on VB Initproperties

You may wonder why we need the InitProperties event since the UserControl property already has an Initialize event in common with Class modules and other objects, such as forms.

The reason that we need InitProperties to initialize default values is that the Initialize event happens too often, that is, every time an instance or your control "wakes up." You only want the default property values to be assigned when the developers first sites a new copy of your control on a container. After that, you want the developer to be able to define persistent property values.

WARNING – Don’t Use the Initialize Event to Set an ActiveX Control’s Default Property Values : If you put code to initialize properties to their default values in your custom ActiveX control’s Initialize event instead of in the InitProperties event, then you will have some very frustrated developers on your hands. Your default values will override the values the developer has assigned at design time every time the developer runs an application using your control.

The Property Bag is a persistent UserControl object containing the values of your control’s custom, extender, and delegated properties. In fact, the Property Bag is so persistent that it doesn’t get destroyed with the instances of the UserControl. This means you can store property values in the Property Bag just before an instance of the UserControl is destroyed and then retrieve the stored values when a new instance of the UserControl "wakes up" in another part of the development life cycle.

The Property Bag has two methods to store and retrieve values respectively:

  • The WriteProperty method

  • The ReadProperty method

You must know how to manipulate the Property Bag in the following situations that we discuss in the sections immediately following this one:

  • You store property values into the PropertyBag by calling its WriteProperty method in the WriteProperties event procedure.

  • You retrieve property values from the PropertyBag by calling its ReadProperty method in the ReadProperties event procedure.

  • You ensure that the WriteProperties event will fire by calling the PropertyChanged method. You’ll usually do this in the Property Let procedures of your custom properties or at other appropriate places in your code where the storage value of a property changes.

—-

The operating environment fires a UserControl‘s ReadProperties and WriteProperties events whenever it thinks that the instantiated object’s properties need to be re-initialized (ReadProperties event fires) or stored for safekeeping (WriteProperties event fires).

This arrangement makes it much easier for you, the control author, to manage these properties since you don’t have to think about all the possible occasions when property values might need reading or writing. You simply need to put code for reading and writing property values in two centralized places: the ReadProperties and WriteProperties event procedures.

Both the ReadProperties and WriteProperties event procedures receive a single parameter named PropBag. This PropBag parameter obviously represents the Property Bag object that holds the UserControl‘s property values.

The PropertyBag object represented by the PropBag parameter has one method for reading properties (ReadProperty) and another for writing properties (WriteProperty).

Usually, the only code you need to write in the ReadProperties event procedure will be a series of calls to the ReadProperty method so you can retrieve persistent values for individual properties.

Conversely, the only code you usually need to write in the WriteProperties event procedure will be a series of calls to the WriteProperty method so you can store persistent values of individual properties.

Visual Basic fires the UserControl‘s WriteProperties event just before it fires the UserControl’s Terminate event provided that at least one property value has changed. In other words, the WriteProperties event fires whenever the current instance of the control is about to be destroyed and any property values that you want to persist have changed and, therefore, need to be saved.

As its name implies, you use the WriteProperties event procedure to save persistent property values. The specific mechanism you use to save property values is to call the WriteProperty method of the Property Bag for each property whose value you wish to save. The Property Bag is available in the event procedure of the WriteProperties event as a parameter named PropBag. The example code in Listing 13.7 shows how you would call the Property Bag‘s WriteProperty method to save individual property values. Notice that we use whatever repository has been storing the property value as the source for the current value: at times this might be a private memory variable, and at other times it might be a property of a constituent control (as in the final line before the End Sub).


USING THE WRITEPROPERTIES EVENT PROCEDURE TO SAVE PROPERTY VALUES TO THE PROPERTY BAG

Private Sub UserControl_WriteProperties (PropBag As PropertyBag)          ‘—Store the values of the custom properties to the Property Bag
      PropBag.WriteProperty  "BackColor", BackColor
      PropBag.WriteProperty  "Celsius", m_Celsius
      PropBag.WriteProperty  "Fahrenheit", m_Fahrenheit
      PropBag.WriteProperty  "TemperatureDate", m_TemperatureDate
      PropBag.WriteProperty  "Caption", lblCaption.Caption
End Sub

The system automatically fires the WriteProperties and ReadProperties events whenever it thinks you may need their services. To ensure that the system knows a property has changed, you have to call the PropertyChanged method. An example of this would be when you change the value of a Private variable that implements the value of a property. The system will have no way of knowing that this variable is connected with a property, and therefore it will not fire the WriteProperties event based solely on the change you have made.

In such cases, you can call the PropertyChanged method. This method informs the system that a particular property has changed and so ensures that the WriteProperties event will fire before the current instance of the control is destroyed. If you’ve written the appropriate code in the WriteProperties xvent, then your property values will be stored in the Property Bag.

You should call the UserControl‘s PropertyChanged method whenever you do something in code that will cause a change to a property whose value you wish to persist. The most typical place for you to call the PropertyChanged method would be in a Property Let or Property Set procedure. Note that we check the CanPropertyChange method that we discuss in "Calling the CanPropertyChange Method Before Allowing a Property Value to Change."

CALLING THE PropertyChanged METHOD TO ENSURE THAT WRITEPROPERTIES WILL FIRE

Property Let Celsius(sValue As Single)
   If CanPropertyChange("Celsius") Then                   ‘—assign incoming value to be stores in Private variable
      m_Celsius = sValue     
      PropertyChanged ("Celsius")                                  ‘—invoke UserControl’s PropertyChanged method so it knows to trigger WriteProperties and store new value     
      Slider1.Value = m_Celsius                                      ‘—perform other housekeeping specific to this application
      RecalcFahrenheitFromCelsius sValue
      DisplayTempsFromSlider
   End If
End Property

 

The ReadProperties event fires when a custom control is reinstantiated at some point in the development cycle (the Project where it resides has been retrieved and its container has been instantiated, the developer has just entered run mode from the design mode, or the developer has just returned to design mode from run mode).

Notice that we said that ReadProperties fires when the custom control is re-instantiated. We used this phrasing to purposely exclude the case when the developer places an instance of the control on its container for the first time from the Toolbox. For such first-time instantiation, the ReadProperties event doesn’t fire. Instead, the InitProperties event fires (see "Using the InitProperties Event to Set Default Starting Property Values"). The ReadProperties event, as its name implies, is the event that you will use to restore the values of properties that have been kept in the Property Bag. The Property Bag appears in the ReadProperties event procedure as a parameter named PropBag. You call PropBag’s ReadProperty method for each property whose value you wish to restore.

Notice that the ReadProperty method takes two arguments: the name of the property as a string and then a default value for the property (in case the property’s value has not been initialized in the Property Bag).

We store the results of each call to ReadProperties in the appropriate variable or control property that implements the property within this control.


USING THE READPROPERTIES EVENT PROCEDURE TO RESTORE PERSISTENT PROPERTY VALUES FROM THE PROPERTY BAG

Private Sub UserControl_ReadProperties (PropBag As PropertyBag)
      m_Celsius = PropBag.ReadProperty("Celsius", 30)
      m_TemperatureDate = PropBag.ReadProperty _
      ("TemperatureDate", DateSerial(1997, 1, 1))
      m_caption = PropBag.ReadProperty ("Caption", Extender.Name)
      BackColor = PropBag.ReadProperty  ("BackColor", Ambient.BackColor)      
      lblCaption.Caption = m_caption                                        
End Sub

Visual Basic PropertyBags to remember Parameters-Its in the Bag

Monday, September 29th, 2008

Recalling UserControl Properties

Standard controls have properties you can set using the object browser.  The next time you bring up your VB program for editing you need to be able to recall the state of these settings.  Example #3 on this page  shows how to use a PropertyBag to remember these settings.

 

             

  BagMan PropertyBag Example

Storage to the Bag

Save to the Bag – Fill up the object to be saved to disk Stuff it in the Bag – The actual file operation to put on disk

 Private Sub cmdSave_Click()

  Dim objBag As New PropertyBag

    With objBag
        .WriteProperty "Str", "A string"
        .WriteProperty "Num", 666
        .WriteProperty "Bool", False
        .WriteProperty "Mascot", SuperBagMan.Picture

        SaveBagContents .Contents, App.Path & "\Things.bag"
    End With
   
    Set objBag = Nothing

End Sub  

                                                                                                               

Private Sub SaveBagContents(Contents As Variant, FilePath As String)

  Dim FileNum As Integer

    FileNum = FileSystem.FreeFile()

    Open FilePath For Binary As FileNum
        Put #FileNum, , Contents
    Close FileNum

End Sub

 

Retrieval from the Bag

Recall the Bag contents from disk Dump the Bag – The actual file operation to get contents from disk

 Private Sub cmdLoadBag_Click()

    Dim objBag As New PropertyBag
    Dim TestInt As Integer
   
    BagReadOut.Text = ""

    With objBag
        .Contents = LoadBagContents(App.Path & "\Things.bag")
              
        Display "Str = " & .ReadProperty("Str", "[No value]")
        Display "Num = " & .ReadProperty("Num", "[No value]")
        Display "Bool = " & .ReadProperty("Bool", "[No value]")
        Display "———————————————–"
        Display "The next value is purposely left off the storage list and thus it uses the default value specified in the .ReadProperty statement"
        Display "NotInBag = " & .ReadProperty("NotInBag", "[No value]")
       
        Set Image1.Picture = .ReadProperty("Mascot", "[No value]")
       
        TestInt = CInt(.ReadProperty("Num", "[No value]"))
       
    End With
   
    Set objBag = Nothing

End Sub

                                                                                                      

Private Function LoadBagContents(FilePath As String) As Variant

  Dim FileNum As Integer
  Dim tempContents As Variant

    FileNum = FileSystem.FreeFile()

    Open FilePath For Binary As FileNum
        Get #FileNum, , tempContents
    Close FileNum

    LoadBagContents = tempContents

 

How to Register an OCX File

Tuesday, September 9th, 2008

If you are receiving errors about an ocx file, registering the file may solve the problem. To register an ocx file simply follow the simple steps below.

  • 1.Locate the file using windows explorer or My Computer. Alternatively search for the filename.
  • 2.Hold down the shift key and right click on the file. Then click ‘Open With…’ from the menu.
  • 3.An ‘Open With’ dialog box should appear. Click the button ‘Other…’.
  • 4.Navigate to your windows\system32 directory and select the file ‘RegSvr32.exe’. Do a file search for it if you have trouble locating the exact folder. On Windows 2000 it is typically located in c:\WINNT\System32. Click Open to select the file. Then click OK on the ‘Open With’ dialog.
  • 5.You should see a message indicating the file was successfully registered. If you see an error message, try restarting your computer and going through the above process again.

Writing a Custom Control for Visual Basic

Tuesday, September 9th, 2008

First Phase is always looking for example code to allow untangling very poorly written explanations.

Variable Visibility

You can pass variables / objects back and forth between a Visual Basic Form and a UserControl.  This archive has source code showing you how to do this:

     Scribble.zip 

 

You can make properties for the following things: Forms, UserControls and Class Modules. Basically any element that will behave as an object.

When to use properties?

Properties are handy when you want to generalize your code: if you’re changing a setting of something, it might be better to create it as a property. Especially if you might have a need to get a return value as well. The property code can then do some additional stuff, such as switching form’s menu items automatically to correct value, so you don’t need to do it from whereever you set the property.

Property Passing

This accesses a property of the Custom Control

Parent Form Custom Control

 

ParentForm.Caption=UserControl1.Caption  

Dim m_Caption As String

Public Property Get Caption() As String
   Caption = m_Caption
End Property

Custom Control to Parent Form:   You call the property from a form the usercontrol is placed on.  

This Sets a property of the Custom Control

Parent Form Custom Control

 

UserControl1.Caption = "This is my control!"

Dim m_Caption As String

Public Property Let Caption(ByVal NewCaption As String)
    m_Caption = NewCaption
End Property

The difference betweeen Property Let and Property Set  — Property Let is used when you pass a variable. Set is used when you pass an object.

Object Passing

This accesses an object of the Custom Control

Parent Form Custom Control

 

Set ParentForm.Picture = UserControl.Picture

Dim m_Picture As IPictureDisp      ‘ –reference to "Ole Automation" required! by default it is included

Public Property Get Picture() As IPictureDisp
    Set Picture = m_Picture
End Property

This sets an object of the Custom Control

Parent Form Custom Control

 

Set UserControl1.Picture = Picture1.Picture

Dim m_Picture As IPictureDisp

Public Property Set Caption(ByRef NewPicture As IPictureDisp)
    Set m_Picture = NewPicture
End Property

Some notes about the examples

I kept the examples as clean as possible. For this reason, I didn’t include additional coding that would redraw the usercontrol for example. Redrawing would be placed in the property handling as otherwise your control would never change. It is a good idea to make a general redrawing procedure within your usercontrol to keep it visually updated with ease.

Adding it all up

– use a property instead of a sub or function if you need to also get the value
– use a sub if you just need to set something
– use a function if you need to set something and require a return value of the result (such as if the function succeeded)
– Property Get works with any data, be it a regular variable or an object
– Property Let is for regular variables
– Property Set is for objects

You can also specify parameters for property methods

A common example of this is when writing a collection class.

Property Get Item(ByVal Index As Long) As MyClassType
   Set Item = BaseCollection(Index)
End Property

Property Set Item(ByVal Index As Long, ByRef pObject As MyClassType)
   Set BaseCollection(Index) = pObject
End Property

The function signatures (type and number of arguments) for the Get and Set/Let methods must match, save for the additional final parameter on the Set/Let routine which is what is being assigned to the property.

As Merri mentioned, Property Set is called when you assign an object reference using the Set keyword. The object is passed by reference. Property Let is called when you assign a value type (Long, String etc.) optionally using the (deprecated) Let keyword, and it is passed by value.

So, you would use the above property Get/Set methods like this:
Dim AnObject As MyClassType
Set AnObject = MyCollectionClass.Item(5) ‘ Get
Set MyCollectionClass.Item(5) = AnObject ‘ Set

 

It works, but you may notice that the built-in VB Collection class has a slightly neater syntax: 

  • Set AnObject = MyCollection(5)

To accomplish this, you need to set the Item property as the default method of your collection class. To do this, click anywhere in your procedure, and from the Tools menu, select Procedure Attributes. Click Advanced to expand the dialog, and from the Procedure ID dropdown, select (Default). This will enable the use of the shorthand syntax shown above.

Inheritance

 

Hierachical Usage of UserControls

I want to be able to use a UserControl inside of a UserControl in order to be able to build a hierachy through reuse of my work.  However how can I do this?  My initial experiments show a UserControl set inside another UserControl does not have visibility of the higher level controls objects.

General Notes

  1. At the level of the form that holds a custom control you will see that the   UserControl_Initialize()  will run even though you have not hit the go button.
  2. I have not yet found how I can set a property and have the Custom Control recall it without the containing form "reminding" in some manner its identity.  I have a piece of code where there are 32 of the same custom control in a control array.  If I could set a property at design time like a standard control this custom control could know where to look for a PropertyBag. Unfortunately my custom control has resisted remembering any of the properties I defined.

Recalling UserControl Properties

See this article for more on PropertyBags