Creating ComponentOne VSFlexGrid on the fly and adding it to Form is an easy task. In this blog we will explain how you can fill VSFlexGrid with data once it is added to Form at runtime. This blog is targeting the developers who are in love with VSFlexGrid and still work in ActiveX environment.

There can be many user scenarios for this like users can create data sheet with VSFlexGrid and then generate/ save an Excel file with this data. Another example is when we don't want to have a VSFlexGrid at design time and want to add VSFlexGrid to the form on button click event at runtime.

In VB6, you need VBControlExtender object for dynamically adding a control to the Controls collection using the Add method.

Steps for adding VSFlexGrid at runtime using VBControlExtender object

1. Add reference for ComponentOne VSFlexGrid in your VB6 project. For that go to Project menu and choose References. It will list all installed/ registered ActiveX controls. Select ComponentOne VSFlexGrid from there and click OK.

AddReferenceVSFlexGrid

2. Then add VBControlExtender object.
VBControlExtender object is used because it provides a generic set of properties, events, and methods to the developer for dynamically adding control. Add this line of code at top of form


Option Explicit
Dim WithEvents dynamicVSFlexGrid As VBControlExtender


3. Add license for ComponentOne VSFlexGrid control


Dim StrLicenseKey As String
StrLicenseKey = Licenses.Add("VSFlexGrid8.VSFlexGridADO", "O0OOEC742")


4. Now you are ready to assign VSFlexGrid control to the VBControlExtender variable and add it on to the Form's controls collection using Add method


Set dynamicVSFlexGrid = Form1.Controls.Add("VSFlexGrid8.VSFlexGridADO", "VSFlexGrid81")



5. With "dynamicVSFlexGrid.object" you can access the VSFlexGrid object and it's properties/ methods


Dim r&, c&
With dynamicVSFlexGrid.object
For r = 1 To .Rows - 1
For c = 1 To .Cols - 1
.TextMatrix(r, c) = "r" & r & "c" & c
Next
Next
End With
dynamicVSFlexGrid.Height = 6000
dynamicVSFlexGrid.Width = 7000
dynamicVSFlexGrid.Visible = True



6. You can also attach any event for this dynamically added VSFlexGrid control through VBControlExtender object's ObjectEvent event which you can use to parse any event raised by the dynamically added VSFlexGrid.


Private Sub dynamicVSFlexGrid_ObjectEvent(Info As EventInfo)
' Program the events of the control using Select Case.
Select Case Info.Name
Case "MouseDown"
MsgBox ("Cell is Clicked")
Case "KeyPress"
MsgBox ("Key is pressed")
End Select
End Sub


Download CreateVSFlexGridDynamiCally sample