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.

StepsTo connect to the database and set up the transaction:

  1. Double-click in an empty area of the form.

    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, System.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 Closing from the list of events in the drop-down list at the top right.

    The Form1_Closing event handler displays.

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

    Private Sub Form1_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
       myTrans.Disconnect()
       Application.Exit()
    End Sub
    

StepsTo disconnect from the database in C#:

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

    private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
    {
       myTrans.Disconnect();
       Application.Exit();
    }