'Create Option Buttons Dynamically?
Q. I plan to read in some questions for a questionnaire from a text file. Each
question may have several option buttons associated with it. Is there any way
to code in a variable number of option buttons, so that one question will have 5
options, another 4, another 12, etc.?
A. Keywords: Load statement, Control Arrays
You will need a separate array of option buttons for each question on your form.
There are two ways to manage the arrays:
1. You could determine the maximum number of option buttons needed for
a question and draw them on the form. Those that are not actually needed can be
made invisible. This method is simple, but wasteful of resources.
2. You could initialize each array with just one option button (element 0) and
then add buttons as necessary this way:
For i = 1 To QuestionCount - 1
Load optQuestion2(i)
Next
Thanks to: Marc Ross, Bob Walsh
'-----------------------------------
'Burt Abreu
'Updated 09/24/99 for VB 6
'-----------------------------------
In Visual Basic 6.0 it is now possible to create a control dynamically at runtime
using the ADD method of the controls collection. I copied this example directly
from MSDN. There is more information online and it seem there may be other ways
of creating objects dynamically but the discussion was a bit advanced for me.
This example declares an object variable of type CommandButton using the WithEvents
keyword, allowing you to program the events of the control. The object variable is
set to the reference returned by the Add method. To try the example, paste the code
into the Declarations section and run the project.
Option Explicit
Private WithEvents btnObj As CommandButton
Private Sub btnObj_Click()
MsgBox "This is a dynamically added button."
End Sub
Private Sub Form_Load()
Set btnObj = Controls.Add("VB.CommandButton", "btnObj")
With btnObj
.Visible = True
.Width = 2000
.Caption = "Hello"
.Top = 1000
.Left = 1000
End With
End Sub
Downloads
In IE right-click and select 'Save Target As...' or in Netscape
right-click and select 'Save Link As...'
View Plain Text
Not Available
Not Available