Tải bản đầy đủ (.pdf) (6 trang)

Tài liệu Add and Delete Rows in a Dataset with ADO.NET pdf

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (21.94 KB, 6 trang )

4.2 Add and Delete Rows in a Dataset with ADO.NET
Again using the OleDbDataAdapter and OleDbCommandBuilder objects, this How-To
shows you how to use unbound controls with the dataset to add and delete rows from
SQL Server.
As with editing and updating data, you need to be able to add and delete rows using the
dataset. How do you perform this task?
Technique
The main difference between this technique and the previous one will be which action
command you will use with the DataAdapter object. You will also be presented with the
Add method on the Rows collection.
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.2. When the form loads, click on the Load
List button to display the customers that begin with the letter A. Click the Add button.
You will notice that the fields have now taken on a sunken look and that they are cleared.
Fill in the Customer ID and Company Name text boxes with AAA1 and Another
Example. Now click Save. If you move off the record and move back on, you will notice
that the value has been saved. Now select the new record you added, and click the Delete
button. The record disappears, and the list box is updated to reflect the deletion.
1. Make a copy of the form you created in the last How-To.
2. Add two buttons for adding and deleting records, setting the properties as listed
here in Table 4.3.
Table 4.3. Add and Delete Buttons Property Settings
Object Property Setting
Button Name
Caption
btnAdd
&Add
Button Name
Text
btnDelete


&Delete
3. Add the following line of code where you placed the other module-level variable
declarations. This variable will be set to True in the btnAdd click event, and it can
be used when saving the record.
4. Dim mblnAdd As Boolean
5. Enter the following code to the Click event btnAdd. The first task is to set the
mblnAdd variable to True. Then the routine clears the current text in the text
boxes. It also enables the text boxes by calling ActiveEditing.
6. Private Sub btnAdd_Click(ByVal sender As System.Object,
7. ByVal e As System.EventArgs) Handles btnAdd.Click
8.
9. Dim oCtl As Object
10. Dim strName
11.
12. mblnAdd = True
13.
14. ' Clear the fields
15. For Each oCtl In Me.Controls
16.
17. If TypeOf oCtl Is TextBox And oCtl.name <> "txtCustLimit" Then
18.
19. strName = Mid(oCtl.Name, 4)
20.
21. ' By trapping the exception this way, errors are ignored.
22. Try
23. oCtl.text = ""
24. Catch oexp As Exception
25. End Try
26.
27. End If

28.
29. Next
30.
31. ActivateEditing(True)
32.

33. End Sub
34. Replace the SaveRecord routine with the following code in the form that you
created for this How-To. The first change is to add the lines of code that test
mblnAdd; if they're True, call the NewRow method off the dataset's Tables
collection, specifying the Customers table. The DataRow returned is assigned to
mdrCustIndiv. You can then enter the other changes wherever the blnAdd variable
is queried.
35. Private Sub SaveRecord()
36.
37. Dim oCtl As Object
38. Dim strName As String
39.
40. If mblnAdd Then
41. mdrCustIndiv = mdsCustIndiv.Tables("Customers").NewRow
42. End If
43.
44. ' Start the editing in the datarow.
45. mdrCustIndiv.BeginEdit()
46.
47. ' Run through the text boxes on the form, and
48. ' if they match up with a field from the record,
49. ' place the value back in the record.
50. For Each oCtl In Me.Controls
51.

52. If TypeOf oCtl Is TextBox Then
53.
54. strName = Mid(oCtl.Name, 4)
55.
56. ' By trapping the exception this way, errors are ignored.
57. Try
58. mdrCustIndiv(strName) = oCtl.text
59. Catch oexp As Exception
60. End Try
61.
62. End If
63.
64. Next
65.
66. ' Finish the editing of the datarow
67. mdrCustIndiv.EndEdit()
68.
69. Try
70.
71. If mblnAdd Then
72. mdsCustIndiv.Tables("Customers").Rows.Add(mdrCustIndiv)
73. End If
74.
75. ' Create an instance of the command builder
76. Dim ocbCustIndiv As OleDb.OleDbCommandBuilder
77. ocbCustIndiv = New OleDb.OleDbCommandBuilder(modaCustIndiv)
78.
79. If mblnAdd Then
80. ' Have the command builder create an Insert SQL command
81. modaCustIndiv.InsertCommand = ocbCustIndiv.GetInsertCommand

82. Else
83. ' Have the command builder create an update SQL command
84. modaCustIndiv.UpdateCommand = ocbCustIndiv.GetUpdateCommand
85. End If
86.
87. ' Perform the specified SQL command; then close the connection
88. modaCustIndiv.Update(mdsCustIndiv, "Customers")
89. mdsCustIndiv.Tables("Customers").AcceptChanges()
90.
91. ' Close the connection
92. If mblnAdd Then
93. modaCustIndiv.InsertCommand.Connection.Close()
94. LoadList()
95. Else
96. modaCustIndiv.UpdateCommand.Connection.Close()
97. End If
98.
99. Catch excData As Exception
100. MessageBox.Show("Error Occurred: " & excData.Message)
101. End Try
102.
103. End Sub
104. Enter the following code to the Click event btnCancel.
105. Private Sub btnCancel_Click(ByVal sender As System.Object, _
106. ByVal e As System.EventArgs) Handles btnCancel.Click
107.
108.
' Cancel the current editing.
109.
110. If mblnAdd Then

111. mblnAdd = False
112. End If
113.
114. LoadIndividual()
115. ActivateEditing(False)
116.
117. End Sub
118. Enter the following code to the Click event btnDelete. Follow the
comments to see what is happening.
119. Private Sub btnDelete_Click(ByVal sender As System.Object,
120. ByVal e As System.EventArgs) Handles btnDelete.Click
121.
122. Dim ocbCustIndiv As OleDb.OleDbCommandBuilder
123.
124. Try
125.
126. ' Delete the record from the datarow object
127. mdrCustIndiv.Delete()
128.
129. ' Instantiate the command builder
130. ocbCustIndiv = New OleDb.OleDbCommandBuilder(modaCustIndiv)
131.
132. ' Have the command builder create a Delete SQL command
133. modaCustIndiv.DeleteCommand = ocbCustIndiv.GetDeleteCommand
134.
135. ' Perform the specified SQL command; then close the connection
136. modaCustIndiv.Update(mdsCustIndiv, "Customers")
137. mdsCustIndiv.Tables("Customers").AcceptChanges()
138.
139. ' Close the connection

140. modaCustIndiv.DeleteCommand.Connection.Close()
141.
142. Catch excData As Exception
143. MessageBox.Show("Error Occurred: " & excData.Message)
144. End Try
145.
146. LoadList()
147. ActivateEditing(False)
148.
149. End Sub
How It Works
When a user clicks the Add button, the text boxes are all blanked out, and the mblnAdd
flag is set as True. Then, after the user adds his information and clicks the Save button,
the new record is added back to the server. If the Cancel button is clicked, the individual
customer to whom the list is currently pointed is loaded into the text boxes. When the
Delete key is pressed, the current record is deleted from the server. Then the customer list
is refreshed, and the first customer in the list is displayed in the text boxes.
Comments
As you can see, adding and deleting a record does not take much more than editing and
updating a record using ADO.NET. Using the commands in this How-To and the prior
one, you can set it up to handle updating and canceling of multiple records as well.

×