4.1 Edit DataandUpdateChanges That AreMadetoanADO.NET DataSet Object Listing and viewing data is easy. What you really need to do is to be able to edit andupdate data. You know you can use the DataSet object and some of its objects and methods to perform this task. How do you edit andupdatedata using the DataSet object? Technique In this How-To, you will use the DataAdapter, DataSet, DataTable, and DataRow objects. You have experienced some of the properties and methods of each of these objects before. In this chapter, you are going to be using the following properties and methods thatare shown in Table 4.1. Table 4.1. DataAdapter, DataSet, DataTable, and DataRow Properties and Methods Object /Method Property Description DataAdapter Fill Fills DataSet and DataTable objects. CommandBuilde r GetUpdateComman d Creates anUpdate command and places it into the data adapter's UpdateCommand property. DataAdapter UpdateCommand Holds the SQL statement for the update. DataAdapter Close Closes the connection off the UpdateCommand. The syntax is dataadapter.UpdateCommand.Connect.Close() . DataAdapter Update Performs the update command against the dataset. DataSet Tables Represents a collection of tables found within a dataset. DataSet Rows Contains a collection of rows within a specified table in a dataset. DataSet AcceptChanges Sends the changes back to the server. DataRow ToString Retrieves the data from the column that is specified in the DataRow and returns it as a string value. DataRow BeginEdit Begins the editing of a DataRow, allowing you to replace values in the columns. DataRow EndEdit Completes the editing of a DataRow. You will see these objects with their properties and methods used in the following steps. Steps Open and run the VB.NET-Chapter 4 solution. From the main form, click on the command button with the caption How-To 4.1. When the form loads, click on the Load List button to display the customers that begin with the letter A. Click the Edit button. You will notice that the fields have now taken on a sunken look. Place the cursor into the City field and change the value to Dunkirk. Now click Save. If you move off the record and move back on, you will notice that the value has been saved. This form looks similar to the form created in Chapter 1. The difference is that this time you will not be using controls thatare bound at design time. You can see the form in Figure 4.1. 1. Create a new Windows Form. 2. Add the following controls, setting the properties as listed in Table 4.2. Table 4.2. Controls Property Settings Object Property Setting Label Name Caption Label1 Customer TextBox Name Text txtCustLimit A Button Name Caption btnLoadList Load List ListBox Name lstCustomers Label Caption Customer ID Label Caption Company Name Label Caption Contact Label Caption Contact Title Label Caption Address Label Caption City Label Caption Region Label Caption Country Label Caption Phone Label Caption Fax TextBox Name txtCustomerID TextBox Name txtCompanyName TextBox Name txtContact TextBox Name txtContactTitle TextBox Name txtAddress TextBox Name txtCity TextBox Name txtRegion TextBox Name txtPostalCode TextBox Name txtCountry TextBox Name txtPhone TextBox Name txtFax Button Name Caption btnEdit &Edit Button Name Caption btnSave &Save Button Name Caption btnCancel &Cancel 3. Note Notice that the Text property of the text boxes is not being set at design time. In Chapter 1, "Developing Windows Forms Using Bound Controls," they were set to columns of a dataset that was included on the form. In this How-To, they will be set at run-time. 4. In the class module for the form, add the following three Private declarations just below the line of code that reads Windows Form Designer generated code. These three objects will be used throughout the form. 5. Dim mdsCustIndiv As New DataSet() 6. Dim modaCustIndiv As OleDb.OleDbDataAdapter 7. Dim mdrCustIndiv As DataRow 8. Enter the following code as the Click event for btnLoadList: 9. Private Sub btnLoadList_Click(ByVal sender As System.Object, _ 10. ByVal e As System.EventArgs) Handles btnLoadList.Click 11. 12. '-- Move the loading of the list to a subroutine for 13. ' additional(calls) 14. LoadList() 15. 16. End Sub 17. Create the LoadList routine by entering the following code into the form you created for this How-To. This code creates and fills a data table using a data adapter. The string that the data adapter uses creates a Select statement by using the txtCustLimit text box. The DataSource, DisplayMember, and ValueMember properties of the list box are then bound. Last, the LoadIndividual routine is called, which is described in the next step. 18. Private Sub LoadList() 19. 20. Dim odaCustList As OleDb.OleDbDataAdapter 21. Dim dtCustList As DataTable = New DataTable() 22. 23. Dim strSQL As String 24. 25. '-- Create the SQL String 26. strSQL = "Select CustomerID, CompanyName " & _ 27. From Customers Where CustomerID Like '" & _ 28. Me.txtCustLimit.Text & "%'" 29. 30. 31. '-- Set up the exception catch 32. Try 33. 34. '-- Create an instance of the data adapter; then fill the data 35. table 36. odaCustList = New OleDb.OleDbDataAdapter(strSQL, _ 37. BuildCnnStr("(local)", "Northwind")) 38. odaCustList.Fill(dtCustList) 39. 40. '-- Bind the datato the list box 41. lstCustomers.DataSource = dtCustList 42. lstCustomers.DisplayMember = "CompanyName" 43. lstCustomers.ValueMember = "CustomerID" 44. 45. LoadIndividual() 46. Catch oexpData As OleDb.OleDbException 47. MsgBox(oexpData.Message) 48. End Try 49. 50. End Sub 51. Create the LoadIndividual routine by entering the following code in the form you created for this How-To. Taking the SelectedItem from the list box, a data adapter is created, and a dataset is filled. Next, the individual DataRow is created. Last, each of the TextBox controls is loaded with the value from the column with the corresponding name. Notice the use of the Try-Catch-End-Try to ignore controls that don't have a like column in the DataRow. 52. Private Sub LoadIndividual() 53. 54. Dim strSQL As String 55. Dim strName As String 56. Dim oCtl As Object 57. 58. mdsCustIndiv.Clear() 59. 60. If Me.lstCustomers.SelectedIndex <> -1 Then 61. 62. Try 63. '-- Load the individual record into the dataset 64. strSQL = "Select * from Customers Where CustomerID = '" & 65. Me.lstCustomers.SelectedItem(0) & "'" 66. modaCustIndiv = New OleDb.OleDbDataAdapter(strSQL, _ 67. BuildCnnStr("(local)", "Northwind")) 68. 69. '-- Fill the dataset 70. modaCustIndiv.Fill(mdsCustIndiv, "Customers") 71. 72. '-- Grab the individual data row 73. mdrCustIndiv = mdsCustIndiv.Tables("Customers").Rows(0) 74. 75. Catch oexpData As OleDb.OleDbException 76. 77. MessageBox.Show("Error loading individual data: " _ 78. & oexpData.Message) 79. Exit Sub 80. 81. End Try 82. 83. '-- Run through the text boxes on the form, and 84. '-- if they match up with a field from the record, 85. ' load them. 86. 87. For Each oCtl In Me.Controls 88. 89. If TypeOf oCtl Is TextBox Then 90. 91. strName = Mid(oCtl.Name, 4) 92. 93. '-- By trapping the exception this way, errors are ignored. 94. Try 95. oCtl.text = mdrCustIndiv(strName).ToString 96. Catch oexp As Exception 97. End Try 98. 99. End If 100. 101. Next 102. 103. End If 104. End Sub 105. Enter the following code to the Click event for lstCustomers: 106. Private Sub lstCustomers_Click(ByVal sender As Object, 107. ByVal e As System.EventArgs) Handles lstCustomers.Click 108. 109. '-- Fill the current list item's individual dataset 110. LoadIndividual() 111. 112. End Sub 113. Enter the following code to the Click event for btnEdit: 114. Private Sub btnEdit_Click(ByVal sender As System.Object, 115. ByVal e As System.EventArgs) Handles btnEdit.Click 116. 117. '-- Enable the editing of the form 118. ActivateEditing(True) 119. 120. End Sub 121. Create the ActivateEditing routine by entering the following code in the form you created for this How-To. Introduced in Chapter 1, this code goes through each of controls on the form, looking for text boxes, then setting the BorderStyle and BackColor properties based on whether the controls areto be enabled or disabled. The Enabled property of each control is then set as well. 122. Private Sub ActivateEditing(ByVal bEnable As Boolean) 123. 124. 125. Dim oCurr As Object 126. 127. '-- Loop through each of the controls on the form 128. For Each oCurr In Me.Controls() 129. 130. '-- Check to see if the control is a text box 131. If TypeOf oCurr Is TextBox And oCurr.Name <> "txtCustLimit" Then 132. 133. '-- If so, toggle the properties 134. If bEnable Then 135. 136. oCurr.BorderStyle() = _ 137. System.Windows.Forms.BorderStyle.Fixed3D 138. 139. oCurr.BackColor() = System.Drawing.Color.White 140. 141. Else 142. 143. oCurr.BorderStyle() = _ 144. System.Windows.Forms.BorderStyle.FixedSingle 145. 146. oCurr.BackColor() = Me.BackColor 147. 148. 149. End If 150. 151. oCurr.Enabled = bEnable 152. 153. End If 154. Next 155. 156. End Sub 157. Enter the following code to the Click event btnSave: 158. Private Sub btnSave_Click(ByVal sender As System.Object, _ 159. ByVal e As System.EventArgs) Handles btnSave.Click 160. 161. '-- Save the information 162. SaveRecord() 163. 164. '-- Disable the text boxes 165. ActivateEditing(False) 166. 167. End Sub 168. Create the SaveRecord routine by entering the following code in the form that you created for this How-To. Using a DataRow object, the BeginEdit method is called, and then each of the controls is stored back into the columns of the same names, if they exist. The EndEdit method is then called to complete the editing of the DataRow. A CommandBuilder object is created to create the Update command for the DataAdapter object. The DataAdapter Update method is called toupdate the dataset with the data changed and then the AcceptChanges of the DataSet object. This accepts all the changes for all the objects and posts the data back to the server. Finally, the connection is closed for the UpdateCommand of the DataAdapter object. 169. Private Sub SaveRecord() 170. 171. Dim oCtl As Object 172. Dim strName As String 173. 174. '-- Start the editing in the datarow. 175. mdrCustIndiv.BeginEdit() 176. 177. '-- Run through the text boxes on the form, and 178. '-- if they match up with a field from the record, 179. '-- place the value back in the record. 180. For Each oCtl In Me.Controls 181. 182. If TypeOf oCtl Is TextBox Then 183. 184. strName = Mid(oCtl.Name, 4) 185. 186. '-- By trapping the exception this way, errors are ignored. 187. Try 188. mdrCustIndiv(strName) = oCtl.text 189. Catch oexp As Exception 190. End Try 191. 192. End If 193. 194. Next 195. 196. '-- Finish the editing of the data row 197. mdrCustIndiv.EndEdit() 198. 199. Try 200. 201. '-- Create an instance of the command builder 202. Dim ocbCustIndiv As OleDb.OleDbCommandBuilder 203. ocbCustIndiv = New OleDb.OleDbCommandBuilder(modaCustIndiv) 204. 205. '-- Have the command builder create anupdate SQL command 206. modaCustIndiv.UpdateCommand = ocbCustIndiv.GetUpdateCommand 207. 208. '-- Perform the update SQL command; then close the connection 209. modaCustIndiv.Update(mdsCustIndiv, "Customers") 210. mdsCustIndiv.Tables("Customers").AcceptChanges() 211. modaCustIndiv.UpdateCommand.Connection.Close() 212. 213. 214. Catch excData As Exception 215. 216. End Try 217. 218. End Sub 219. Enter the following code to the Click event btnCancel: 220. Private Sub btnCancel_Click(ByVal sender As System.Object, _ 221. ByVal e As System.EventArgs) Handles btnCancel.Click 222. 223. '-- Use the BindingContext class to cancel the current editing. 224. LoadIndividual() 225. ActivateEditing(False) 226. 227. End Sub Figure 4.1. Although this looks like the form created in Chapter 1, you have more control over this version with unbound controls. How It Works When the user clicks on the btnLoadList Button, the lstCustomers list box is loaded via the odaCustList data adapter and dtCustList data table. The first customer's information is then loaded in the text boxes on the right side of the form. When the btnEdit button is clicked, the look of the text boxes is changed to sunken, and they are enabled for editing of the text. After changing the data, when the user clicks on the btnSave button, the data is then stored back into the server, and the text boxes are changed to disabled. If the btnCancel is clicked, the text boxes are changed to disabled. Comments Although it takes a bit more code to handle the editing and updating of data with unbound controls versus bound controls, you might like it better because you can control the code. With bound controls, the code is written for you. The code that is displayed here can be modified to be more generic so that you don't have to write individual routines for each form. . Edit Data and Update Changes That Are Made to an ADO. NET DataSet Object Listing and viewing data is easy. What you really need to do is to be able to edit. CommandBuilde r GetUpdateComman d Creates an Update command and places it into the data adapter's UpdateCommand property. DataAdapter UpdateCommand