Connecting to the database

Now you add code so that the connection to the database is made when the form is loaded. You also want to establish the relationship between each DataWindowControl and the Transaction object at the same time, because the association only needs to be made once per session.

In Visual Studio, the techniques for adding an event handler are different in Visual Basic and C#.

StepsTo connect to the database and set up the transaction:

  1. In Visual Basic, double-click in an empty area of the form. In C#, display events in the Properties window and double-click the Load event.

    This creates an event handler for the form’s Load event and opens the code editor:

    [Visual Basic]
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    
    End Sub
    
    
    [C#]
    private void Form1_Load(object sender, EventArgs e)
       {
    
       }
    
  2. Type the following in the Form1_Load event handler (add semicolons to the end of each line for C#):

    myTrans.Connect()
    dwCustList.SetTransaction(myTrans)
    dwCustomer.SetTransaction(myTrans)
    

    This code connects to the database and associates the connected Transaction object with each of the DataWindowControls.

Disconnecting from the database

When you drag a Transaction object to a form, it is added to the form’s components list, and is automatically disconnected and disposed of when the form is closed. If you do not use drag-and-drop, you need to disconnect from the database when the form is closed.

StepsTo disconnect from the database in Visual Basic:

  1. In the code editor, select FormClosing from the list of events in the drop-down list at the top right.

    The Form1_FormClosing event handler displays.

  2. Enter the following code to disconnect from the database and exit the application when the form is closed:

    myTrans.Disconnect()
    Application.Exit()
    

StepsTo disconnect from the database in C#:

  1. Open the Design view for the form and double-click the FormClosing event in the Properties window.

  2. Enter the following code in the FormClosing event handler to disconnect from the database and exit the application when the form is closed:

    myTrans.Disconnect();
    Application.Exit();