Walkthrough: saving data in transactions

Source: Internet
Author: User
Walkthrough: saving data in transactions

This walkthrough demonstrates how to use the system. Transactions namespace to save data in a transaction. This example usesMERsAndOrdersTable.

Prerequisites

This drill requires access to the northwind sample database. For information on setting the northwind sample database, see How to: Install the sample database.

Create a Windows Application

The first step is to create a "Windows ApplicationProgram".

Create a new windows Project
    1. In Visual Studio, create a new project from the File menu ".

    2. Name the projectSavingdatainatransactionwalkthrough.

    3. Select "Windows Applications" and click "OK ". For more information, see create a Windows-based application.

      Create the savingdatainatransactionwalkthrough project and add it to Solution Explorer.

Create a database data source

In this step, use the data source Configuration Wizard to createMERsAndOrdersThe data source of the table.

Create a data source
    1. Click "show data source" on the "data" menu ".

    2. In the "Data Source" window, select "Add new data source" to start the "Data Source Configuration Wizard ".

    3. On the "Select data source type" Page, select "Database" and click "Next ".

    4. On the "select your data connection" Page, perform the following operations:

      • If the drop-down list contains data connections to the northwind Sample Database, select this connection.

        -Or-

      • Select "New Connection", start the "Add/modify connection" dialog box, and create a connection to the northwind database. For more information, see the "Add/modify connection" dialog box (general ).

    5. If the database requires a password, select this option to include sensitive data, and then click "Next ".

    6. On the "Save connection string to application configuration file" page, click "Next ".

    7. Expand the "table" node on the "select database object" page.

    8. SelectMERsAndOrdersAnd then click Finish ".

      "Northwinddataset" is added to your project and appears in the "Data Source" window.MERsAndOrdersTable.

Add controls to a form

You can drag some items from the "Data Source" window to your form to create a data binding control.

Create a data binding control on Windows Forms
    • Expand the customers node in the data source window.

    • Drag the main "MERs" node from the "Data Source" window to "form1.

      The datagridview control and toolbar used for navigation record appear on the form. The components column contains the northwinddataset, mermerstableadapter, bindingsource, andBindingnavigator.

    • Drag the related "orders" Node (the related sub-Table node under the "fax" column, rather than the main "orders" node) to the form under "customersdatagridview.

      ADatagridview. Orderstableadapter andBindingsourceAppears in the component bar.

Add reference to system. Transactions assembly

Transaction usageSystem. TransactionsNamespace. By default, project references to the system. Transactions assembly are not added, so you need to manually add them.

Add reference to the system. Transactions DLL file
    1. Select "add reference" from the "project" menu ".

    2. Select system. Transactions on the. NET tab and click OK ".

      References to "system. Transactions" are added to the project.

Modify the code in the saveitem button of bindingnavigator

By default, because the first table has been placed on your formCodeAddedBindingnavigatorSaveClickEvent. You need to manually add code to update all additional tables. For this walkthrough, We Will refactor the existing save code of the click event handler originating from the Save button, and create more methods to provide specific update functions based on whether to add or delete rows.

Modify automatically generated save code
  1. Double-click "save" on "customersbindingnavigator" (with a floppy disk icon ).

  2. Replace with the following codeCustomersbindingnavigatorsaveitem_clickMethod:

    Copy code in Visual Basic

     Private   Sub Customersbindingnavigatorsaveitem_click ( Byval Sender As System. object, Byval E As System. eventargs )_Handles Customersbindingnavigatorsaveitem. Click updatedata () End   Sub      Private   Sub Updatedata () Me . Validate () Me . Customersbindingsource. endedit () Me . Ordersbindingsource. endedit () using updatetransaction As   New Transactions. transactionscope deleteorders () deletecustomers () addnewcustomers () addneworders () updatetransaction. Complete () northwinddataset. acceptchanges ()End Using End   Sub     

    C # copy code

    Private VoidCustomersbindingnavigatorsaveitem_click (Object sender, eventargs e) {updatedata ();}Private VoidUpdatedata (){This. Validate ();This. Customersbindingsource. endedit ();This. Ordersbindingsource. endedit ();Using(System. Transactions. transactionscope updatetransaction =NewSystem. Transactions. transactionscope () {deleteorders (); deletecustomers (); addnewcustomers (); addneworders (); updatetransaction. Complete (); northwinddataset. acceptchanges ();}}

    J # copy code

    Private VoidCustomersbindingnavigatorsaveitem_click (Object sender, system. eventargs e) {updatedata ();}Private VoidUpdatedata (){This. Validate ();This. Customersbindingsource. endedit ();This. Ordersbindingsource. endedit (); system. Transactions. transactionscope updatetransaction =NewSystem. Transactions. transactionscope (); {deleteorders (); deletecustomers (); addnewcustomers (); addneworders (); updatetransaction. Complete (); northwinddataset. acceptchanges ();}}

The sequence of coordinated changes to relevant data is as follows:

    • Delete a sub-record (in this caseOrdersDelete records in the table)

    • Delete the parent record (in this caseMERsDelete records in the table)

    • Insert the parent record (in this caseMERsInsert records in the table)

    • Insert a sub-record (in this caseOrdersInsert records in the table)

Delete existing order
  • Set the followingDeleteordersMethod To add to "form1 ":

    Copy code in Visual Basic

     Private   Sub Deleteorders () Dim Deletedorders As Northwinddataset. ordersdatatable deletedorders = ctype (northwinddataset. Orders. getchanges (data. datarowstate. Deleted), _ northwinddataset. ordersdatatable) If   Not Isnothing (deletedorders)Then      Try Orderstableadapter. Update (deletedorders) Catch Ex As Exception MessageBox. Show ( "Deleteorders failed" ) End   Try      End   If      End   Sub     

    C # copy code

    Private VoidDeleteorders () {northwinddataset. ordersdatatable deletedorders; deletedorders = (northwinddataset. ordersdatatable) northwinddataset. Orders. getchanges (datarowstate. Deleted );If(Deletedorders! =Null){Try{Orderstableadapter. Update (deletedorders );}Catch(System. Exception ex) {MessageBox. Show ("Deleteorders failed");}}}

    J # copy code

    Private VoidDeleteorders () {northwinddataset. ordersdatatable deletedorders; deletedorders = (northwinddataset. ordersdatatable) northwinddataset. get_orders (). getchanges (datarowstate. Deleted );If(Deletedorders! =Null){Try{Northwinddatasetorderstableadapter. Update (deletedorders );}Catch(System. Exception ex) {MessageBox. Show ("Deleteorders failed");}}}

Delete existing customers
  • Set the followingDeletecustomersMethod To add to "form1 ":

    Copy code in Visual Basic

     Private   Sub Deletecustomers () Dim Deletedcustomers As Northwinddataset. customersdatatable deletedmers MERs = ctype (northwinddataset. Customers. getchanges (data. datarowstate. Deleted), _ northwinddataset. customersdatatable) If   Not Isnothing (deletedcustomers) Then      Try Customerstableadapter. Update (deletedcustomers) Catch Ex As Exception MessageBox. Show ( "Deletecustomers failed" & Vbcrlf & Ex. Message)End   Try      End   If      End   Sub     

    C # copy code

    Private VoidDeletecustomers () {northwinddataset. customersdatatable deletedmers MERS; deletedcustomers = (northwinddataset. customersdatatable) northwinddataset. MERs. getchanges (datarowstate. Deleted );If(Deletedcustomers! =Null){Try{Customerstableadapter. Update (deletedcustomers );}Catch(System. Exception ex) {MessageBox. Show ("Deletecustomers failed");}}}

    J # copy code

    Private VoidDeletecustomers () {northwinddataset. customersdatatable deletedmers MERS; deletedcustomers = (northwinddataset. customersdatatable) northwinddataset. get_mers MERs (). getchanges (datarowstate. Deleted );If(Deletedcustomers! =Null){Try{Northwinddatasetcustomerstableadapter. Update (deletedcustomers );}Catch(System. Exception ex) {MessageBox. Show ("Deletecustomers failed");}}}

Add new customer
  • Set the followingAddnewcustomersMethod To add to "form1 ":

    Copy code in Visual Basic

     Private  Sub Addnewcustomers () Dim Newcustomers As Northwinddataset. customersdatatable newcustomers = ctype (northwinddataset. Customers. getchanges (data. datarowstate. Added), _ northwinddataset. customersdatatable) If   Not Isnothing (newcustomers) Then      Try Customerstableadapter. Update (newcustomers) Catch Ex As Exception MessageBox. Show ( "Addnewcustomers failed" & Vbcrlf & Ex. Message)End   Try      End   If      End   Sub     

    C # copy code

    Private VoidAddnewcustomers () {northwinddataset. customersdatatable newcustomers; newcustomers = (northwinddataset. customersdatatable) northwinddataset. MERs. getchanges (datarowstate. Added );If(Newcustomers! =Null){Try{Customerstableadapter. Update (newcustomers );}Catch(System. Exception ex) {MessageBox. Show ("Addnewcustomers failed");}}}

    J # copy code

    Private VoidAddnewcustomers () {northwinddataset. customersdatatable newcustomers; newcustomers = (northwinddataset. customersdatatable) northwinddataset. get_customers (). getchanges (datarowstate. Added );If(Newcustomers! =Null){Try{Northwinddatasetcustomerstableadapter. Update (newcustomers );}Catch(System. Exception ex) {MessageBox. Show ("Addnewcustomers failed");}}}

Add new order
  • Set the followingAddnewordersMethod To add to "form1 ":

    Copy code in Visual Basic

     Private   Sub Addneworders () Dim Neworders As Northwinddataset. ordersdatatable neworders = ctype (northwinddataset. Orders. getchanges (data. datarowstate. Added), _ northwinddataset. ordersdatatable) If   Not Isnothing (neworders) Then      Try Orderstableadapter. Update (neworders) Catch Ex As Exception MessageBox. Show ( "Addneworders failed" & Vbcrlf & Ex. Message) End  Try      End   If      End   Sub     

    C # copy code

    Private VoidAddneworders () {northwinddataset. ordersdatatable neworders; neworders = (northwinddataset. ordersdatatable) northwinddataset. Orders. getchanges (datarowstate. Added );If(Neworders! =Null){Try{Orderstableadapter. Update (neworders );}Catch(System. Exception ex) {MessageBox. Show ("Addneworders failed");}}}

    J # copy code

    Private VoidAddneworders () {northwinddataset. ordersdatatable neworders; neworders = (northwinddataset. ordersdatatable) northwinddataset. get_orders (). getchanges (datarowstate. Added );If(Neworders! =Null){Try{Northwinddatasetorderstableadapter. Update (neworders );}Catch(System. Exception ex) {MessageBox. Show ("Addneworders failed");}}}

Run the application

Run the application
    • Press F5 to run the application.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.