Intelligent client data in Visual Basic 2005
Release Date: 7/27/2004
| Update Date: 7/27/2004
Robert Green
Microsoft Corporation
Applicable to:
Microsoft Visual Basic 2005 Beta 1
Summary: This exercise demonstrates several new features in Visual Studio 2005 to help readers develop applications that can access data.
This page
Introduction Prerequisites Creating Data Binding Windows Forms Binding To Existing Controls Creating a pair of multi-Forms To bind the combo box to lookup table Save, Insert, and Delete Record Add Custom Navigation Control to Tableadapter Add Query Back to a Record Small Junction
Introduction
In previous versions of Visual Studio, you need to connect to the data source in the Server Explorer, and drag the table or stored procedure to the form. The results will be pre-configured with SQLConnection and SqldataAdapter, and pre-configured with SELECTCOMMAND, INSERTCOMMAND, DELETECOMMAND, and UPDATECOMMAND. Then, there is a need to perform several time-consuming steps to complete the data binding form, including the DataADAPTER configuration to generate DataSet, add controls to the form, and then add data binding (whether in the code or through the Properties window) .
Visual Studio 2005 introduces Data Sources Window, which can also be set to the server-based data, but also set to local data, web services, and your own business objects. Drag the table to the form Generate a data binding form that can handle most of the steps you need to manually complete in previous versions, including name controls, add name tags to individual controls, and create dataBinding.
In this exercise, you will explore these new data features using Visual Basic 2005.
Back to top
prerequisites
To complete the drill, you must install the following software and components on the development computer:
• Microsoft Visual Studio 2005 Beta 1 • Microsoft SQL Server or Microsoft SQL Server Desktop Engine (MSDE), (MSDE 7.0 or MSDE 2000), and install the Northwind sample database.
Back to top
Create a data binding Windows Form
In this task, you will create a simple data binding form without writing any code. The form will be shown in Figure 1 below.
Figure 1. Example Orders Form
Create a project
1. Start Visual Studio 2005. 2. On the File menu, select New Project. 3. In the Templates pane, select Windows Application. 4. Name the project DataWalkthrough. Click OK.
Add data source
1. On the Data menu, select Show Data Sources. 2. In the Data Sources window, select Add New Data Source. Data Sources represent data that you can use in your application. You can create one or more data sources with Data Source Configuration Wizard for use in your project. These data sources can be server-based databases such as SQL Server and Oracle, local database files such as MSDE or Access, web services, and business objects. 3. Click Next. This will display the Choose A Data Source Type page. 4. Select Database. 5. Click Next. This will display the Choose Your Data Connection page. 6. Click New Connection. 7. Enter the appropriate information to connect to your SQL Server or MSDE instance. 8. In the Select Or Enter A Database Name drop-down list, select Northwind. 9. Click OK. 10. Click Next. This will display the Save Connection String pane. 11. Check Yes, Save the Connection As. This will save the connection string in the new strong type settings, which adds the app.config file. Connection information is now saved in the project level, not in the respective individual forms of use of data. This makes it easy to maintain and change the connection information. 12. If you do not use SQL Server integration security, check Include Sensitive Data. 13. Click Next. This will display the Choose Your Database Objects page. 14. Expand the Tables nodes to view the tables in the database. 15. Select ORDERS, OrderDetails, Customers and Employees tables. You can assign a name to the data collected on this page. Note that the name is default to northwinddatan. 16. Click Finish. The DataSources window is the main window for viewing and handling data that can be used by your project. The Data Sources window displays NorthwindDataSet and Orders, OrderDetails, Customers, and Employees tables. 17. In the Data Sources window, expand the Orders node to view each column in the table shown in Figure 2. Figure 2. Data Sources Window
Use DataSet Designer
In the last task, you have created a dataset. As you will soon see, the Data Sources window makes it easy to create a data binding form. But before performing this task, you can use DataSet Designer to process objects in the data set.
1. In Solution Explorer, double-click NorthWindDataSet.xsd. DataSet Designer displays four Datacomponents that correspond to each table you selected at the time of setting the data source. The data component is a combination of data tables and TableAdapters and is the main items that make up strong type datasets. TableAdapters is a designer generated component created by Visual Studio. They are similar to a strong type data adapter with configured SELECT, INSERT, UPDATE, and DELETE commands. TableAdapter can contain multiple select commands. TableAdapters have a strong type of method for retrieving data and insert, update, and saving data. These methods can be packaged in the PARAMETERS collection. 2. Select the ORDERID column in the ORDERS table. 3. In the Properties window, confirm that the ReadOnly property is set to True. 4. Change the CAPTION attribute to OrderID. In the next task, you will drag the ORDER table field from the Data Source window into the form. This will create data binding controls and tags at the same time. The CAPTION of each field in the ORDERS table will be the default CAPTION of the tag associated with each control. Note You can change the ORDERID to the Order ID in the DataSet Designer surface. However, this will change the Name instead of CAPTION. 5. Highlight the CustomerID column. Change the CAPTION attribute to Customer. 6. Highlight the EmployeeID column. Change the CAPTION attribute to EMPLOYEE. 7. Change other titles as needed. Drag and drop data to the form
In this task, you will drag and drop the table from the Data Sources window to the form. This will automatically create data binding controls to save a lot of time and effort.
1. Return to the design view of the form. 2. In the Data Sources window, expand the ORDERS node to view the columns in the table. 3. Select ORDERID in the ORDERS table. In the drop-down list associated with this field, change the control type to Label. Doing this can change the controls used when dragging and dropping the fields onto the form. You can use any suggested controls, you can also select Customize and select a user control or a third-party control. Note When you select Customize, all currently visible in Toolbox will display a control of a set of new DataBindingProperty, ComplexBindingProperties or LookupBindingProperties.
1. Select the Customerid in the ORDERS table. In the drop-down list associated with this field, change the control type to ComboBox. 2. Select the EmployeeID in the ORDERS table. In the drop-down list associated with this field, change the control type to ComboBox. 3. Select the ORDERS table. In the drop-down list associated with the table, select Details. 4. Drag the ORDERS table from the Data Sources window to the form. The following objects are now displayed in Component TRAY:
• NorthWindDataSet is a dataset that you create when configuring data sources. • ORDERSTABLEADAPTER. This is a TableAdapter with SELECT, INSERT, UPDATE, and DELETE commands associated with the OrderS table. • ORDERSDATACONNECTOR is an instance of System.Windows.Forms.DataConnector. The DataConnector component is designed to simplify the process of binding the control to the underlying data source. DataConnector presented CurrencyManager from the form's bindingContext. It is a method for more easy to use, more intuitive, used to bind controls on the form to data. • ORDERSDATANAVIGATOR is an instance of System.Windows.Forms.DataNavigator. DataNavigator is a standardization means that can be used to simply navigate and manipulate data on Windows Forms. It is used in conjunction with the DataConnector component to traverse data records on the form and interact with them. DataNavigator is a ToolStrip control with buttons for navigating and adding, deleting, and saving records in a record. Note DataNavigator is an optional VCR style control that does not affect any configured DataBinding when deleting it. 5. Select the FREIGHTTEXTBOX control. 6. Expand the DataBinding list in the Properties window, as shown in Figure 3. Note that the FreightTextBox control is bound to the FREIGHT column in the OrdersDataConnector. Figure 3. View control data binding
7. Select ORDERSDATACONNECTOR in Component TRAY. Note that the DataSource property is set to NorthWindDataSet, and the DataMber property is set to Orders. 8. Select the ORDERIDLABEL1 control. Change its BorderStyle property to Fixed3D. 9. From the Debug menu, select START (or press F5). The form will appear and display the order as shown in Figure 4.
Figure 4. Sample form in the example form
10. Use the Move next, Move Previous, Move First, Move, Move First, Move, Move, Move, and the Move in the navigation toolbar. 11. In the Current Position Text box in the navigation toolbar, enter any number between 1 and 830. Press ENTER to move to the record. 12. Turn off the form. 13. In Solution Explorer, click the View Code button. Note The following code during the Form1_Load: Me.OrderstableAdapter.Fill (me.NorthwindDataSet.Orders)
The above code calls the Fill method of the ORDERSTABLEADAPTER. TableAdapter's Fill method is similar to the use of the SqlDataAdapter's Fill method. It retrieves data from the data source and puts these data into the specified data set.
Back to top
Bind to existing controls
In the last task, you create a data binding control by dragging the OrderS table from the Data Sources window. You usually create these controls first, and then you want to bind them. In this task, you will bind to an existing control by dragging the field from the Data Sources window to the control.
Data binding existing control
1. Return to the design view of the form. 2. Add a TextBox to the vicinity of the Customerid combo box in the form. Name the text box as CustomeridTextBox. 3. In the Data Sources window, expand the Orders node. 4. Drag the CustomerId columns in the Orders table to the CustomeridTextBox control. 5. Expand the DataBindings list in the Properties window. Note that the CustomeridTextBox control is bound to the CustomerID column in the OrdersDataConnector. Note The control type of the CustomerID field is still set to ComboBox in the Data Sources window. When dragging the Customerid field to an existing control, the control will not be changed to the combo box. 6. From the Debug menu, select Start (or press F5). The form will appear and the CustomerID is displayed in the combination box and the text box you just added. 7. Turn off the form. Back to top
Create a pair of multi-forms
In this task, you will add a related table to the data binding form. You will use the pop-up menu to specify the primary - from the relationship without having to define this relationship with the code.
Add related tables to the form
1. Return to the design view of the form. 2. Select OrdersDataConnector in Component Tray. 3. From the Data menu, select Configure Master Details. This will display the Add Reeted Database UI dialog. 4. Select ORDERS as the parent table. 5. Select ORDER DETAILS as a child table. 6. Select Grid as a UI Style. 7. Click OK. This will add a DataGridView to the form. Alternatively, the following objects will be added to CompanyTTRAY:
• ORDER_DETAILSTABLEADAPTER • FK_ORDER_DETAILS_ORDERSDATACONNECTOR 8. Select the Order_DetailsDataGridView control. Note that the DataGridView's DataSource property is set to fk_order_details_ordersDataConnector. 9. Select the fk_order_details_ordersDataConnector in Component TRAY. Note that the DataSource property is set to the OrdersDataConnector, and the DataMber property is set to fk_order_details_orders. The fk_order_details_ordersDataConnector has a relationship between the OrderS table and the Order Details table.
Configure DataViewGrid
1. Select the ORDER_DETAILSDataGridView control. 2. Click the arrow that appears in the upper right corner of the grid. This will display the Actions pop-up menu. 3. Select Auto Format. 4. In the Auto Format dialog, select Professional 2. 5. Click OK. 6. Select the Edit Columns in the ActionS pop-up menu. In the Edit Columns dialog box, you can add or delete columns, change the display order column in the grid, change column header text, and so on. 7. Click OK. 8. From the Debug menu, select START (or press F5). The form will appear and display the order and related order details as shown in Figure 5.
Figure 5. Samples in the example form and detailed information record
9. Scroll between the respective records and view the details of the details of each order displayed in the grid. 10. Turn off the form. 11. Switch to the code view of the form. Note that the following code has been added to the Form1_Load process: Me.Order_detailstableadapter.Fill (me.northwinddataSet.Order_details) Back to top
Bind the combo box to the lookup table
This form currently contains two combo boxes. You want them to display the name of the customer and the name of the staff, rather than displaying CustomerID and EMPLOYEEID. In this task, you will bind the combo box to the appropriate lookup table to display the name of the required.
Bind the CustomerID combo box to the Customers table
1. Return to the design view of the form. 2. Select the CustomerIDCOMBOBOX control. 3. In the Properties window, expand the list associated with the DataSource property. The DataConnector of the ORDERS and ORDER DETAILS tables will appear in this list because they have been added to the Component Tray. However, you need the data in the Customers table, so you have to find and select the Customers table. 4. Expand the Other Data Sources node. 5. Expand the Project Data Sources node. 6. Expand the NorthwindDataSet node. 7. Select Customers. This will set the DataSource property of the CustomeridComboBox control to CustomersDataConnector, as shown in Figure 6.
Figure 6. Setting the DataSource of the combo box
Note that the following objects are now added to the form of the form:
• CustomersTableAdapter • CustomersDataConnector 8. Sets the displaymember property to CompanyName. Note that the displayed column is from the Customers table. 9. Set the valueMember property to CustomerID. 10. Expand the DataBindings list in the Properties window. 11. Right-click the Text property and select RESET. 12. Expand the list associated with the SelectedValue property. 13. Expand the OrdersDataConnector node. 14. Select CustomerID. Note that the displayed columns come from the Orders table.
Add an expression to the Employee table
The Employee table contains fields corresponding to LastName and FirstName. However, you want to display the last name and name at the same time in the combo box. In this task, you will add a column that combines the last name and name to the Employee table.
1. Switch to DataSet Designer. 2. Right-click on the Employees table. 3. From the Add menu, select Column. 4. In the Properties window, set the NAME property to EMPLOYEENAME. 5. Set the Expression property to: LastName ',' firstname
Bind the EmployeeID combo box to the Employees table
1. Return to the design view of the form. 2. Select the EmployeeiDComboBox control. 3. In the Properties window, expand the list associated with the DataSource property. DataConnector of Orders, Order Details, and Customers tables is displayed in this list. However, you need data in the Employees table, so you have to find and select the Employees table. 4. Expand the Other Data Sources node. 5. Expand the Project Data Sources node. 6. Expand the NorthwindDataSet node. 7. Select EMPLOYEES. This will set the DataSource of the EmployeeiDComboBox control to EmployeesDataConnector.
Note the following objects in the Component Tray of the form:
• EmployeESTABLEADAPTER • EMPLOYEESDATACONNECTOR
1. Set Displaymember to EMPLOYEENAME. 2. Set the valuemember property to EMPLOYEEID. 3. Expand the DataBindings list in the Properties window. 4. Right-click the Text property and select RESET. 5. Expand a list of associated with the SelectedValue property. 6. Expand the ORDERSDATACONNECTOR node. 7. Select EMPLOYEEID. 8. From the Debug menu, select START (or press F5). 9. Use the buttons you just added to scroll between each record. The form will appear and the customer name and staff name are displayed in their respective combo boxes. 10. Turn off the form.
Back to top
Save, insert, and delete records
The DataNavigator toolbar contains some built-in features. You have already understood that you can navigate data records in the form. You may have noticed that the Add and Delete buttons on the DataNavigator toolbar are available. Select the Add button to add a blank line to the Orders DataTable, and select the Delete button to remove the current line from the Orders DataTable.
The add and delete buttons do not operate the underlying data. They only operate the ORDERS table in the DataSet. No permanent changes will be made unless you save the changes to the basic data. Of course, this is not a new concept for processing data using ADO.NET. You will have to write your own logic to save. This is why the Save button on the DataNavigator toolbar is disabled by default. Unless you write code to save the data, you will not do anything when you click the button.
In this task, you will add code to save and delete the main records and details of the form on the form. The code for saving and deleting records requires the primary relationship between Orders and Order Details.
You do not need to add code that performs inserted operation, because DataNavigator can add a blank line. However, in this task, you will write some code to automatically populate the Ship TO column recorded by ORDERS.
Save record
1. Return to the code view of the form. 2. To add an attribute to store an error message, add the following code: Dim DataErrorvalue As String
Private property DataError () AS STRING
Get
Return DataErrorvalue
END GET
Set (byval value as string)
DataErrorvalue = Value
End set
End Property
3. To create a function for saving records, add the following code after the Form1_Load method: private function savechanges () AS Booleantry
ORDERSDATACONNECTOR.Endedit ()
FK_Order_Details_OrdersDataConnector.endedit ()
Catch exception
Me.DataError = EX.MESSAGE
Return False
END TRY
Try
OrderStableAdapter.Update (me.northwinddata.com.orders)
Order_detailstableadapter.Update (_
Me.NorthWindDataSet.Order_Details)
Catch exception
Me.DataError = EX.MESSAGE
Return False
END TRY
Return True
END FUNCTION
Note that the UPDATE method has multiple overloads. The overloads used here accept specific DataTable. 4. Return to the design view of the form. 5. Select the ORDERSDATANAVIGATOR control. You will find that selecting controls in Component TRAY is extremely convenient. 6. Select the DataNavigatorsaveItem control. This is the Save button in the DataNavigator toolbar. 7. Set the enabled property to True. 8. In the Properties window, click the Events button. This is the flash button in the Properties window. 9. Double-click the Click event. Note The events list in the Properties window is the new features in Visual Basic 2005. It makes it easy to create a handler or assign an existing handler for an event. 10. Add the following code to the DataNavigatorsaveItem_click process: if SaveChanges () = true kil
Messagebox.show ("Changes Were Saved", "ORDERS", _
MessageboxButton.ok, MessageBoxicon.information)
Else
Messagebox.show (Me.DataError, "Orders", _
MessageboxButton.ok, MessageBoxicon.information)
END IF
11. From the Debug menu, select START (or press F5). 12. Enter a value for the Ship to Region of the first order. 13. Click the Save button. 14. Close the form. 15. From the Debug menu, select Start (or press F5). You will see the Ship Region value you entered.
Add record
In this task, you will write code so that when a customer in the Customer Combination box is selected, the Ship to field in the Orders table is automatically populated.
1. Return to the design view of the form. 2. Select the CustomerIDCOMBOBOX control. 3. In the Properties window, click the Events button. 4. Double-click the SelectedIndexchanged event. 5. Add the following code to the CustomeridComboBox_Selected Indelected process: if customeridcomboBox.selectedIndex <> -1 Then
DIM CustomerDataRow As NorthwinddataSet.customersRowcuStomerDataRow = NorthwinddataSet.customers (_
CustomeridComboBox.selectedIndex)
With CustomerDataRow
ShipNameTextBox.text = .companyname
ShipaddressTextBox.text = .address
ShipcityTextBox.text = .city
IF CustomerDataRow.isRegionnull Then
ShipregionTextBox.Text = ""
Else
ShipregionTextBox.text = .region.tostring
END IF
IF CustomerDataRow.ispostalcoDenull Then
Shippostalcodetextbox.text = ""
Else
ShippostalcodeTextBox.text = .postalcode
END IF
ShipCountryTextBox.text = .country
End with
END IF
6. From the Debug menu, select Start (or press F5). 7. Click the Add New button in the navigation toolbar. The total number of orders displayed in the navigation toolbar will increase. Note Please note that you are still in the location of the first order instead of the order you are adding. This is a problem in Beta 1. To move to the location you are adding, press the Move Last button in the navigation toolbar. 8. Select a customer from the Customer drop-down list. Note that the SHIP TO control is filled with appropriate information about the selected customer. 9. Select a staff from the Employee drop-down list. 10. Enter the following information to complete the order orderdate = Today's Date
RequiredDate = Any Date After Today
ShippedDate = any date after Today
Shipvia = Any Number from 1 to 3
FREIGHT = 50.00
11. Click DataGridView. Note that the ORDERID in the grid is set to the correct number. 12. Enter a productID between 1 and 77. 13. Enter a Quantity and a Unitprice. 14. Enter a number for Discount. Note You must enter the corresponding content for discount because the column is not empty. 15. Add additional order details record as needed. 16. Click the Save button. 17. Close the form. 18. From the Debug menu, select START (or press F5). 19. To confirm that the order has been added, navigate to the last Orders record. You will see the ORDER and Order Details record you entered.
Delete Record
1. Return to the code view of the form. 2. To create a function used to delete records, add the following code: private function deleteorder () as boolean
Dim ORDERDATAROWVIEW As System.Data.DataRowView
ORDERDATAROWVIEW = OrdersDataConnector.current
ORDERDATAROWVIEW.ROW.DELETE ()
Try
Dim DetailsDataRowView As System.Data.DataRowViewFor Each DetailsDataRowView in _
FK_ORDER_DETAILS_ORDERSDATACONNECTOR.LIST
DetailsDataRowView.row.Delete ()
NEXT
Catch exception
Me.DataError = EX.MESSAGE
Return False
END TRY
Try
ORDERSDATACONNECTOR.Endedit ()
FK_Order_Details_OrdersDataConnector.endedit ()
Catch exception
Me.DataError = EX.MESSAGE
Return False
END TRY
Try
Order_detailstableadapter.Update (_
Me.NorthWindDataSet.Order_Details)
OrderStableAdapter.Update (me.northwinddata.com.orders)
Catch exception
Me.DataError = EX.MESSAGE
Return False
END TRY
Return True
END FUNCTION
3. Return to the design view of the form. 4. Select the ORDERSDATANAVIGATOR control. 5. Select the DataNavigatorDeleteItem control. This is the DELETE button in the DataNavigator toolbar. 6. In the Properties window, click the Events button. 7. Double-click the Click event. 8. Add the following code to the DataNavigatorDeleteItem_click process: if deleteorder () = true kil
Messagebox.show ("Order Was Deleted", "ORDERS", _
MessageboxButton.ok, MessageBoxicon.information)
Else
Messagebox.show (Me.DataError, "Orders", _
MessageboxButton.ok, MessageBoxicon.information)
END IF
9. From the Debug menu, select START (or press F5). 10. Navigate to the last Orders record. 11. Click the DELETE button. 12. Turn off the form. 13. From the Debug menu, select START (or press F5). You will once again see 830 orders. 14. To confirm that the order has been deleted, navigate to the last Orders record. You will not see the order you added. 15. Close the form.
Back to top
Add a custom navigation control
DataNavigator is a convenient control, but you don't have to use it. You can create your own controls for navigation. In this task, you will add your own buttons to your form to process navigation between individual records, as well as processing saving, insert, and deleting records.
Add your own data navigation button
1. Return to the design view of the form. 2. Select the ORDERSDATANAVIGATOR control. 3. Set the Visible property to False. Note If you are willing, you can also delete ORDERSDATANAVIGATOR. 4. Add a Menustrip control to the form. The Menustrip control is a container of the menu structure on the form. When you enter each menu command in Menustrip, you can actually add ToolstripMenuItem objects to Menustrip. 5. Click the menu bar in the first Type Here text box. 6. Enter first as the text of the menu item. 7. Press the Tab key to switch to the next menu item. 8. Enter the previous. 9. Press the Tab key to switch to the next menu item. 10. Enter next. 11. Press the Tab key to switch to the next menu item. 12. Enter Last. 13. Press the TAB key to switch to the next menu item. 14. Enter the Add. 15. Press the TAB key to switch to the next menu item. 16. Enter the delete. 17. Press the TAB key to switch to the next menu item. 18. Enter SAVE. 19. Adjust the size of MenustriP1 as needed to increase its size. 20. Click the arrow appearing on the right of the menu bar. This will display the Actions pop-up menu. Note Each menu item has an arrow and its own ActionS pop-up menu. Here you need the entire menu of the Actions pop-up menu, so you must click the arrow of the menu bar. As an alternative, you can use the menu bar items attribute in the Properties window. 21. Select Edit Items. This will display items collections editor. 22. In the items list, select ToolStripseParator. 23. Click Add. 24. Click the UP arrow three times to make the separator between the Last and Add menu items. 25. Click OK. Add data navigation code
1. Select the FirstToolstripMenuItem control. This is the first menu command in the menu bar. 2. In the Properties window, click the Events button. 3. Double-click the Click event. 4. Add the following code to the firstToolstripMenuItem_click process: ORDERSDATACONNECTOR.MOVEFIRST
5. Select the PrevioustoolStripMenuItem control. This is the previous menu command in the menu bar. 6. In the Properties window, click the Events button. 7. Double-click the Click event. 8. Add the following code to the PrevioustoolStripMenuItem_Click process: OrdersDataConnector.MovePrevious
9. Select the NextToolStripMenuItem control. This is the Next menu command in Menustrip. 10. In the Properties window, click the Events button. 11. Double-click the Click event. 12. Add the following code to the NEXTTOOLSTRIPMENUITEM_CLICK process: ORDERSDATACONNECTOR.MOVENEXT
13. Select the LastToolStripMenuItem control. This is the Last menu command in Menustrip. 14. In the Properties window, click the Events button. 15. Double-click the Click event. 16. Add the following code to the LastToolStripMenuItem_click process: OrdersDataConnector.MovelAst
DataConnector brings a lot of data tasks. This makes the DataConnector become a simple and intuitive way to process data in the application. Add code for performing add, delete, and save operations
1. Select the AddToolStripMenuItem control. This is the Add menu command in the menu bar. 2. In the Properties window, click the Events button. 3. Double-click the Click event. 4. Add the following code to the AddToolStripMenuItem_click process: ORDERSDATACONNECTOR.ADDNEW ()
By default, DataNavigator's add button calls the above code. 5. Select the DeleToolstripMenuItem control. This is the Delete menu command in the menu bar. 6. In the Properties window, click the Events button. 7. Double-click the Click event. 8. Add the following code to the deletetoolstripMenuItem_click process: if deleteorder () = true kil
Messagebox.show ("Order Was Deleted", "ORDERS", _
MessageboxButton.ok, MessageBoxicon.information)
Else
Messagebox.show (Me.DataError, "Orders", _
MessageboxButton.ok, MessageBoxicon.information)
END IF
The above code is the same as the code you associated with the Detanavigator's delete button. 9. Select the SaveToolstripMenuItem control. This is the SAVE menu command in the menu bar. 10. In the Properties window, click the Events button. 11. Double-click the Click event. 12. Add the following code to the SaveToolstripMenuItem_click process: if SaveChanges () = True THEN
Messagebox.show ("Changes Were Saved", "ORDERS", _
MessageboxButton.ok, MessageBoxicon.information)
Else
Messagebox.show (Me.DataError, "Orders", _
MessageboxButton.ok, MessageBoxicon.information)
END IF
The above code is the same as the code you associated with the SAVE button of DataNavigator. 13. From the Debug menu, select START (or press F5). 14. Use the buttons you just added to scroll between each record. 15. Add a new order according to the previous practice. Save the order. 16. Delete the order. The behavior of the form should be the same as the behavior you use when using the DataNavigator toolbar. 17. Close the form.
Back to top
Add queries to TableAdapter
When you drag the ORDERS and Order Details tables to the form, you have created TableAdapter. Tableadapter has a method for retrieving data and performing insertion, update, and deleting operations. These methods are based on INSERT, UPDATE, and DELETE statements or stored procedures.
Not restricted You can only use methods generated by drag and drop. In this task, you will add a query to the Orders TableAdapter to return a separate order instead of all orders.
Add ORDERID-based return order
1. Return to DataSet Designer. 2. Select ORDERSTABLEADAPTER. 3. Right-click ORDERSTABLEADAPTER and select Add Query from the pop-up menu. This will display Data Component Query Configuration Wizard. 4. Click Next. 5. Select CREATE New Stored Procedure. Note If you do not have permissions for creating a stored procedure in the database, you can select Use Sql Statements in this step. 6. Click Next. 7. Select SELECT Which Returns Rows. 8. Click Next. 9. Add the following code to the end of the SELECT statement: where orderid = @ ORDERID10. Click Next. Note If you do not create a new stored procedure, skip to step 14. 11. Name the stored procedure ordeid. 12. Select Yes, CREATE IT IN The Database for Me check box. 13. Click Next. 14. Change the first Method Name to FillbyOrderid. 15. Change the second Method Name to getDatabaseORDERID. 16. Click Finish. Note that the method you add appears in the order of ORDERSTABLEADAPTER, as shown in Figure 7.
Figure 7. Add inquiry to TableAdapter
Back to top
Return a record
In this task, you will change the data entry form to use the query you just created. This will enable the user to return a order instead of all orders.
Restrict the order record from the server
1. Return to the design view of the form. 2. Add a MaskedTextBox to the form. Name it as ORDERIDMASKEDTEXTBOX. 3. Click the arrow that appears on the right side of the shield text box. This will display the Actions pop-up menu. 4. Select Set The Mask Associated with The Control by SETHE MASK Associated. 5. Enter 99999 in the Mask text box. This will limit the data input to a number. 6. Click OK. 7. Add a Button next to the block text box you just added. Name it FindorderButton. Set the TEXT property of the button to Find this ORDER. 8. Add a button next to the shielded text box. Rename it allordersButton. Set the TEXT property of the button to all Orders. 9. Add the following code to the FINDORDERBUTTON_CLICK process: Me.Orderstableadapter.FillbyOrderId (_
Me.NorthWindDataSet.orders, OrderidmasKedTextBox.Text)
OrderidmasKedTextBox.text = ""
10. Add the following code to the AllordersButton_Click process: me.orderstableadapter.Fill (me.NorthwindDataSet.OrDERS)
OrderidmasKedTextBox.text = ""
11. From the Debug menu, select START (or press F5). 12. Enter 10456 in the text box you add. 13. Click Find this ORDER. Note that a set of order records are loaded now. 14. Click All Orders. Note that all order records are loaded into the form again. 15. Close the form.
Back to top
summary
Visual Studio 2005 contains several new features that make it easier to build applications that can access data. The Data Sources window and DataSet Designer provide convenience venues for processing the structure of the underlying data. Drag and drop columns from Data Sources and you can create data binding controls without setting data binding in your code or in the Properties window. TableAdapter and DataConnector components are committed to providing a more intuitive way to manipulate data. Go to the original English page