Netframwork 2.0 (phần 9) doc

50 431 0
Netframwork 2.0 (phần 9) doc

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Lesson 4: Working with Data in DataTable Objects 375 The RowState is used to determine the state of a row. When first populated, the rows in a DataTable have a RowState of Unchanged. Table 7-3 details the different values of the RowState enumeration. Table 7-3 RowState Enumeration Value Description Unchanged No changes have been made since the last AcceptChanges call or since the initial filling of the DataTable. Added This row has been added since the last AcceptChanges call. Modified This row has been updated since the last AcceptChanges call. Deleted This row has been deleted from the DataTable since the last AcceptChanges call. Detached This row has not yet been added to any DataTable.Rows collection. In addition to RowState, each row also maintains different versions after changes are made. These differing versions are accessed by passing a value from the DataRow- Version enumeration as an argument in addition to the column index when accessing the data in a row. For example, you can access the current and original values of a col- umn in a specific DataRow to perform processing prior to calling AcceptChanges. Accepting and Rejecting Changes to a DataTable When all changes to a row are deemed valid, you can accept the modifications by call- ing the DataRow.AcceptChanges method. Calling the AcceptChanges method sets the RowState of the row to Unchanged and commits all current values to original. You can call AcceptChanges on the DataRow, DataTable, or entire DataSet. If you decide to abort changes instead of accepting them, call the RejectChanges method of the DataRow, DataTable, or DataSet. DataTable Events DataTable objects expose several events that are raised when changes are being made to the data in the table. 376 Chapter 7 Create, Add, Delete, and Edit Data in a Disconnected Environment The main events available when working with DataTable objects are listed in Table 7-4. Table 7-4 DataTable Events Event Desription ColumnChanged Raised after a value is inserted into a column ColumnChanging Raised when a value is submitted to change a column RowChanged Raised after a row in the table has been edited RowChanging Raised when a row in the table is edited RowDeleted Raised after a row is marked for deletion RowDeleting Raised when a row is marked for deletion Row Errors When errors are encountered during the processing of DataRows, a value is added to the RowError property. The RowError property is a string that is typically set to an error message describing the error, but it can be set to any string and used as needed in your application. Once a DataRow.RowError property is assigned, the DataTable.HasErrors property is automatically set to True, indicating errors exist in the DataTable. When it is determined that errors exist, you can use the DataTable.GetErrors method to return an array of DataRows containing all rows that have errors or, more specifically, all rows with a RowError value other than null (nothing, or the empty string). To remove an error, set the DataRow.RowError property to an empty string. Quick Check 1. How do you add data to a DataTable? 2. How do you commit pending modifications to the data in a DataTable? Quick Check Answers 1. Create a new DataRow and add it to the DataTable.Rows collection. 2. By calling AcceptChanges on the DataRow, DataTable, or DataSet. Lesson 4: Working with Data in DataTable Objects 377 Lab: Working with Data in a DataTable In this lab you will manipulate the data in a DataTable. � Exercise 1: Working with DataTable Objects This practice will provide code examples that demonstrate adding data to a table, deleting rows in a table, and editing existing values in a data row and how to view the RowState and DataRowVersion information for records in a DataTable. After modifying records, the AcceptChanges and RejectChanges methods will be demonstrated as well. 1. Create a Windows application and name it WorkingWithDataTables. 2. Add a DataGridView to the form and change its Name property to Customers- DataGridVie w. 3. Add a button to the form and set the following properties: ❑ Name = FillTableButton ❑ Text = Fill Table 4. Drop a SqlDataAdapter from the Toolbox onto the form to start the Data Adapter Configuration Wizard. NOTE SqlDataAdapter Toolbox item If the SqlDataAdapter is not in the Toolbox, right-click the Data section of the Toolbox, select Choose Items, and then select the SqlDataAdapter item on the .NET Framework Components tab. Click OK. 5. Select or create a new connection to the Northwind database and click Next. 6. Leave the default option to Use SQL Statements, and then click Next. 7. Type SELECT * FROM Customers on the Generate The SQL Statements page and click Finish. The adapter and related Connection object are added to the form and appear in the component tray. 8. Right-click SqlDataAdapter1 in the component tray and select Generate DataSet. 9. In the Generate DataSet dialog box, replace DataSet1 with NorthwindDataSet and click OK. An instance of the NorthwindDataSet is added to the form and appears in the component tray. 378 Chapter 7 Create, Add, Delete, and Edit Data in a Disconnected Environment Figure 7-11 Form1 in the VS IDE after configuring the DataAdapter and generating the DataSet 10. Add the System.Data.SqlClient namespace to your form. 11. Create a Form Load event handler and add the following code to the Form1_Load event handler: ' VB CustomersDataGridView.DataSource = NorthwindDataset1.Customers ' For this example we will turn off the ability to edit directly in a cell. CustomersDataGridView.MultiSelect = False CustomersDataGridView.SelectionMode = DataGridViewSelectionMode.CellSelect CustomersDataGridView.EditMode = DataGridViewEditMode.EditProgrammatically // C# CustomersDataGridView.DataSource = NorthwindDataset1.Customers; // For this example we will turn off the ability to edit directly in a cell. CustomersDataGridView.MultiSelect = false; CustomersDataGridView.SelectionMode = DataGridViewSelectionMode.CellSelect; CustomersDataGridView.EditMode = DataGridViewEditMode.EditProgrammatically; 12. Create a button-click event handler for the FillTableButton and add the following code: ' VB SqlDataAdapter1.Fill(NorthwindDataset1.Customers) // C# sqlDataAdapter1.Fill(NorthwindDataset1.Customers); Add a button to the form and set the following properties: Lesson 4: Working with Data in DataTable Objects 379 ❑ Name = AddRowButton ❑ Text = Add Row 13. Create a button-click event handler for the AddRowButton and add the following code: ' VB ' Create a new instance of a Customers row. Dim NewRow As NorthwindDataset.CustomersRow = _ CType(NorthwindDataset1.Customers.NewRow, NorthwindDataset.CustomersRow) ' Set the values for each column in the row. With NewRow .CustomerID = "WINGT" .CompanyName = "Wingtip Toys" .ContactName = "Steve Lasker" .ContactTitle = "CEO" .Address = "1234 Main Street" .City = "Buffalo" ._Region = "NY" .PostalCode = "98052" .Country = "USA" .Phone = "206-555-0111" .Fax = "206-555-0112" End With ' Add the new row to the Rows collection of the Customers table. Try NorthwindDataset1.Customers.Rows.Add(NewRow) Catch ex As Exception MessageBox.Show(ex.Message, "Add Row Failed") End Try // C# // Create a new instance of a Customers row. NorthwindDataset.CustomersRow NewRow = (NorthwindDataset.CustomersRow)NorthwindDataset1.Customers.NewRow(); // Set the values for each column in the row. NewRow.CustomerID = "WINGT"; NewRow.CompanyName = "Wingtip Toys"; NewRow.ContactName = "Steve Lasker"; NewRow.ContactTitle = "CEO"; NewRow.Address = "1234 Main Street"; NewRow.City = "Buffalo"; NewRow.Region = "NY"; NewRow.PostalCode = "98052"; NewRow.Country = "USA"; NewRow.Phone = "206-555-0111"; NewRow.Fax = "206-555-0112"; // Add the new row to the Rows collection of the Customers table. 380 Chapter 7 Create, Add, Delete, and Edit Data in a Disconnected Environment try { NorthwindDataset1.Customers.Rows.Add(NewRow); } catch (Exception ex) { MessageBox.Show(ex.Message, "Add Row Failed");} 14. Add the following code to the form class that creates a function to return the CustomersRow selected in the grid: ' VB Private Function GetSelectedRow() As NorthwindDataset.CustomersRow ' Get the selected DataRow Dim SelectedCustomerID As String = _ CustomersDataGridView.CurrentRow.Cells("CustomerID").Value.ToString ' Using the SelectedCustomerID get the selected row. Dim SelectedRow As NorthwindDataset.CustomersRow = _ NorthwindDataset1.Customers.FindByCustomerID(SelectedCustomerID) Return SelectedRow End Function // C# private NorthwindDataset.CustomersRow GetSelectedRow() { // Get the selected DataRow String SelectedCustomerID = CustomersDataGridView.CurrentRow.Cells["CustomerID"].Value.ToString(); // Using the SelectedCustomerID get the selected row. NorthwindDataset.CustomersRow SelectedRow = NorthwindDataset1.Customers.FindByCustomerID(SelectedCustomerID); return SelectedRow; } 15. Add a button to the form and set the following properties: ❑ Name = DeleteRowButton ❑ Text = Delete Row 16. Create a button-click event handler for the DeleteRowButton and add the follow- ing code: ' VB ' Call the Delete method of the selected row to mark it as deleted in the DataTable GetSelectedRow.Delete() // C# // Call the Delete method of the selected row to mark it as deleted in the DataTable GetSelectedRow().Delete(); Lesson 4: Working with Data in DataTable Objects 381 17. Add three buttons to the form and set the following properties: ❑ Name = UpdateValueButton ❑ Text = Update Value ❑ Name = AcceptChangesButton ❑ Text = Accept Changes ❑ Name = RejectChangesButton ❑ Text = Reject Changes 18. Add a TextBox next to the UpdateValueButton and set its Name property to Cell- ValueTextBox. 19. Add three more TextBox objects and set the Name properties to the following: ❑ OriginalDRVTextBox ❑ CurrentDRVTextBox ❑ RowStateTextBox The Form layout should appear similar to Figure 7-12. Figure 7-12 The Form layout 20. Add the following code to the form class that updates the text boxes with the row versions and row state: ' VB Private Sub UpdateRowVersionDisplay() ' Display the Original and Current DataRowVersion of the selected Cell Try CurrentDRVTextBox.Text = GetSelectedRow.Item _ 382 Chapter 7 Create, Add, Delete, and Edit Data in a Disconnected Environment (CustomersDataGridView.CurrentCell.OwningColumn.Name, _ DataRowVersion.Current).ToString Catch ex As Exception CurrentDRVTextBox.Text = ex.Message End Try Try OriginalDRVTextBox.Text = GetSelectedRow.Item _ (CustomersDataGridView.CurrentCell.OwningColumn.Name, _ DataRowVersion.Original).ToString Catch ex As Exception OriginalDRVTextBox.Text = ex.Message End Try ' Display the current RowState of the selected row RowStateTextBox.Text = GetSelectedRow.RowState.ToString End Sub // C# private void UpdateRowVersionDisplay() { // Display the Original and Current DataRowVersion of the selected Cell try { CurrentDRVTextBox.Text = GetSelectedRow() [CustomersDataGridView.CurrentCell.OwningColumn.Name, DataRowVersion.Current].ToString(); } catch (Exception ex) { CurrentDRVTextBox.Text = ex.Message; } try { OriginalDRVTextBox.Text = GetSelectedRow() [CustomersDataGridView.CurrentCell.OwningColumn.Name, DataRowVersion.Original].ToString(); } catch (Exception ex) { OriginalDRVTextBox.Text = ex.Message; } // Display the current RowState of the selected row RowStateTextBox.Text = GetSelectedRow().RowState.ToString(); } Lesson 4: Working with Data in DataTable Objects 383 21. Create an event handler for the UpdateValueButton_Click event and add the fol- lowing code: ' VB GetSelectedRow(CustomersDataGridView.CurrentCell.OwningColumn.Name) = CellValueTextBox.Text UpdateRowVersionDisplay() // C# GetSelectedRow()[CustomersDataGridView.CurrentCell.OwningColumn.Name] = CellValueTextBox.Text; UpdateRowVersionDisplay(); 22. Create an event handler for the CustomersDataGridView_CellClick event and add the following code: ' VB ' Populate the CellValueTextBox with the selected cell CellValueTextBox.Text = CustomersDataGridView.CurrentCell.Value.ToString ' Refresh the other text boxes UpdateRowVersionDisplay() // C# // Populate the CellValueTextBox with the selected cell CellValueTextBox.Text = CustomersDataGridView.CurrentCell.Value.ToString(); // Refresh the other text boxes UpdateRowVersionDisplay(); 23. Create an event handler for the AcceptChangesButton.Click event and add the fol- lowing code: ' VB GetSelectedRow().AcceptChanges() UpdateRowVersionDisplay() // C# GetSelectedRow().AcceptChanges(); UpdateRowVersionDisplay(); 24. Create an event handler for the RejectChangesButton and add the following code: ' VB GetSelectedRow().RejectChanges() UpdateRowVersionDisplay() // C# GetSelectedRow().RejectChanges(); UpdateRowVersionDisplay(); 25. Run the application and click the Fill Table button. 384 Chapter 7 Create, Add, Delete, and Edit Data in a Disconnected Environment 26. Click around the grid and notice that the Original and Current values show as the same, and the RowState display is Unchanged. 27. Now click the cell that contains Maria Anders (in the first row) and type Maria AndersEdited in the CellValueTextBox. 28. Click the UpdateValue button and notice that the value is updated in the grid, the Current and Original text boxes display the different versions of the record, and the RowState has been changed to read Modified. 29. Now click the Add Row button. 30. Scroll down to the bottom of the grid and select one of the cells in the new record (WINGT). Notice that the RowState is Added to reflect that this is a new row, and the Origi- nal text box shows that there is no original data, again because this is a new row. Figure 7-13 Form after clicking the Add Row button 31. Scroll back to the row with the MariaAndersEdited field and select it. 32. Click the RejectChanges button and inspect the row version and row state values. 33. Scroll to the WINGT record and select it. 34. Click the Accept Changes button and inspect the row version and row state values. [...]... XmlDataDocument and syn­ chronize it with the NorthwindDataSet ' VB Dim NwDataDocument As New XmlDataDocument(NorthwindDataset) // C# XmlDataDocument NwDataDocument = new XmlDataDocument(NorthwindDataset); Perfoming an XPath Query on a DataSet You can perform XPath queries against data in a DataSet after synchronizing a DataSet with an XmlDataDocument Pass an XPath query to the XmlDataDocument.DocumentElement.SelectNodes... indices for example: MessageBox.Show(row(1).ToString()) End If Next // C# DataRow row; Xml.XmlDataDocument NwDataDocument = new Xml.XmlDataDocument(NorthwindDataset) Xml.XmlNodeList CustomerNodes = NwDataDocument.DocumentElement.SelectNodes("*"); foreach (Xml.XmlNode xmlNode In CustomerNodes) { row = NwDataDocument.GetRowFromElement(Xml.XmlElement)xmlNode; if (row != null) { // access data through row... DataSet with an XmlDataDocument? A By passing the XmlDataDocument to the DataSet.GetXml method B By declaring a new instance of an XmlDataDocument and passing in the name of the DataSet you want to synchronize with C By calling the XmlDataDocument.Load method D By calling the XmlDataDocument.Synch method 3 How do you execute an XPath query on a DataSet? A Synchronize with an XML document and perform... shows how to execute an XPath query and iterate through the results: ' VB Dim row As DataRow Dim NwDataDocument As New Xml.XmlDataDocument(NorthwindDataset) Dim CustomerNodes As Xml.XmlNodeList = NwDataDocument.DocumentElement.SelectNodes("*") For Each xmlNode As Xml.XmlNode In CustomerNodes row = NwDataDocument.GetRowFromElement(CType(xmlNode, Xml.XmlElement)) If row IsNot Nothing Then 390 Chapter 7 Create,... DataSet using XML ❑ Load a DataSet from an XML stream or document ❑ Write a DataSet as XML data ❑ Load DataSet schema information from an XML stream or document ❑ Write DataSet schema information as XML schema (XSD) ❑ Synchronize a DataSet with an XmlDataDocument ❑ Perform an XPath query on a DataSet ❑ Apply an XSLT transform to a DataSet ❑ Create nested DataRelation objects in a DataSet to represent... // C# NorthwindDataset.ReadXmlSchema("Northwind.xsd"); Synchronizing a DataSet with an XmlDataDocument When working with XML data and DataSet objects, you will typically need to manip­ ulate data through the DataSet classes as well as XML classes available in the NET Framework Keeping your DataSet and XmlDataDocument in synch allows you to pro­ cess the data using whichever method of access you prefer... DataSet can be written out as XML data ■ The schema of a DataSet can be written out as XML Schema (an xsd file) ■ The data in an XML file or document can be loaded into a DataSet ■ The schema information in an xsd file can be loaded into a DataSet ■ A DataSet and an XMLDataDocument can be kept in synch so you can manipu­ late the data and have it be reflected in both objects ■ XPath queries can be performed... XML DataSet objects can be filled from an XML document or an XML stream, and they can load or write out their schema information DataSet objects have several methods for working with XML data that will be described in the following examples After this lesson, you will be able to: ■ Represent data in a DataSet using XML ❑ Load a DataSet from an XML stream or document ❑ Write a DataSet as XML data ❑ Load... with an XML document and perform the XPath query on the raw XML B Pass the XPath query as a string to the DataTable.Select method C Pass the XPath query as a string to the DocumentElement.SelectNodes method of a synchronized XmlDataDocument D Pass the XPath query as a string to the DataTable.Find method 396 Chapter 7 Create, Add, Delete, and Edit Data in a Disconnected Environment Lesson 6: Creating... object’s schema information to a file named Northwind.xsd ' VB NorthwindDataset.WriteXmlSchema("Northwind.xsd") // C# NorthwindDataset.WriteXmlSchema("Northwind.xsd"); Loading a DataSet from an XML Stream or Document To load XML data into a DataSet, use the ReadXml method of the DataSet You can read the XML data directly from a file, or you can read it from a stream Call the ReadXml method of a DataSet to . .Address = " 123 4 Main Street" .City = "Buffalo" ._Region = "NY" .PostalCode = "9 80 52& quot; .Country = "USA" .Phone = " ; 20 6-555 -01 11" . "USA"; NewRow.Phone = " ; 20 6-555 -01 11"; NewRow.Fax = " ; 20 6-555 -01 12& quot;; // Add the new row to the Rows collection of the Customers table. 3 80 Chapter 7 Create, Add, Delete, and. XmlDataDocument and syn- chronize it with the NorthwindDataSet. ' VB Dim NwDataDocument As New XmlDataDocument(NorthwindDataset) // C# XmlDataDocument NwDataDocument = new XmlDataDocument(NorthwindDataset);

Ngày đăng: 07/07/2014, 05:20

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan