Creating a Post_Form_Load Event
Language(s):Visual Basic 6.0
Category(s):Events

Sometimes it is desirable to have a Post_Form_Load event. For example suppose you are using the Data control. Youwant to disable the Edit button if there are no records in the recordset. If you try to test the recordset during theForm_Load event, your code will fail with an 'Object variable or With block variable not set' error because the Recordsetobject of the Data control has not yet been instantiated. Although a Post_Form_Load event is not intrinsic to Visual Basic, it is an easy matter to create your own using atimer control. The following example uses the Post_Form_Load event to disable a command button if the recordset being openedis empty. The example defaults to the Northwind Database that ships with Visual Basic, but the code will work with anydatabase and any recordset.

' 1) Create a new project. Form1 will be created by default.
' 2) Add a Timer, two Command Buttons and a Data control to the Form.
' 3) Paste the following code into the declarations section of Form1:

' --- Begin code for Form1

'Post_Form_Load Event Example
'
'Jon Vote, Idioma Software Inc.
'
'02/2002
'
'www.idioma-software.com

Option Explicit

Private Sub Form_Load()
  
  Dim strDatabaseName As String
  Dim strRecordsource As String
  
  Timer1.Enabled = False
  Timer1.Interval = 100
  
  Me.Caption = "Post Formload Event Example"
  
  Command1.Caption = "&Add"
  Command2.Caption = "&Edit"
  
  strDatabaseName = InputBox$("Database name?", "Get Database Name", _ 
         "C:\Program Files\Microsoft Visual Studio\VB98\NWIND.MDB")
  strRecordsource = InputBox$("Recordsource?", "Get Recordsource", "Orders")
  Data1.DatabaseName = strDatabaseName
  Data1.RecordSource = strRecordsource
    
  'This code will blow up if put in the Form_Load event
  'with an 'Object variable or With block variable not set'
  'error. The Post_Form_Load event solves this problem.
'  If (Data1.Recordset.BOF And Data1.Recordset.EOF) Then
'    Command2.Enabled = False
'  End If
  
   'To trigger the Post_Form_Load event, set on the timer.
   Timer1.Enabled = True
  
End Sub

Private Sub Timer1_Timer()
    
  Timer1.Enabled = False
  Post_Form_Load
 
End Sub

Private Sub Post_Form_Load()
  
  'Now that the form is loaded, we can do this:
  If (Data1.Recordset.BOF And Data1.Recordset.EOF) Then
    Command2.Enabled = False
  End If
  
End Sub

' --- End code for Form1 ---
This article has been viewed 4063 times.
The examples on this page are presented "as is". They may be used in code as long as credit is given to the original author. Contents of this page may not be reproduced or published in any other manner what so ever without written permission from Idioma Software Inc.