ejemplo para actualizar y guardar cambios realizados en un control data grid view
TRANSCRIPT
Ejemplo para actualizar y guardar cambios realizados en un control DataGridview
El ejemplo tiene tres botones , uno para actualizar los cambios realizados en la grilla, otro para eliminar el registro seleccionado y otro para crear uno nuevo
Controles en un windows form
Un DataGridview
Tres controles Button ( btn_delete,
btn_Update, btn_new) para eliminar , guardar
y crear un nuevo registro
Cuatro button ( btn_first, btn_Previous,
btn_next y btn_last) para moverse por los
registros de la tabla usando los métodos
MoveFirst , MoveNext etc.. del componente
Bindingsource
Establecer la cadena de conexión y la
instrucción sql para cargar la tabla en el
datagridview
Código fuente
Texto plano Copiar código fuente Imprimir
1.Option Explicit On 2.Option Strict On 3. 4.' Espacios de nombres 5.' ''''''''''''''''''''''''''''''''''''''
''' 6.Imports System.Data.SqlClient 7. 8.Public Class Form1 9. 10. 'BindingSource 11. Private WithEvents bs As New Bind
ingSource 12. 13. ' Adaptador de datos sql 14. Private SqlDataAdapter As SqlData
Adapter 15. 16. ' Cadena de conexión 17. Private Const cs As String = "Dat
a Source=(local)\SQLEXPRESS;" & _
18. "Initial Catalog=demo_bd;" & _
19. "Integrated Security=true"
20. 21. ' flag 22. Private bEdit As Boolean 23. 24. 25. ' actualizar los cambios al salir 26. ' '''''''''''''''''''''''''''''''
''''''''' 27. Private Sub Form1_FormClosing( _ 28. ByVal sender As Object, _ 29. ByVal e As System.Windows.For
ms.FormClosingEventArgs) _ 30. Handles Me.FormClosing 31. 32. If bEdit Then 33. 'preguntar si se desea gu
ardar 34. If (MsgBox( _ 35. "Guardar cambios
?", _ 36. MsgBoxStyle.YesN
o, _ 37. "guardar")) = Msg
BoxResult.Yes Then 38. 39. Actualizar(False) 40. End If 41. End If 42. End Sub 43. 44. Private Sub Form1_Load( _ 45. ByVal sender As System
.Object, _ 46. ByVal e As System.EventArgs)
Handles MyBase.Load 47. 48. ' propiedades del datagrid
49. ' '''''''''''''''''''''''''''''''''''''
50. With DataGridView1 51. ' alternar color de filas 52. .AlternatingRowsDefaultCe
llStyle.BackColor = Color.FloralWhite 53. .DefaultCellStyle.BackCol
or = Color.Beige 54. ' Establecer el origen de
datos para el DataGridview 55. .DataSource = bs 56. End With 57. 58. ' botones 59. ' '''''''''''''''''''''''''''
'''''''''' 60. btn_Update.Text = "Guardar ca
mbios" 61. btn_delete.Text = "Eliminar r
egistro" 62. btn_new.Text = "Nuevo" 63. 64. btn_first.Text = "<<" 65. btn_Previous.Text = "<" 66. btn_next.Text = ">" 67. btn_last.Text = ">>" 68. 69. ' cagar los datos 70. cargar_registros("Select * Fr
om alumnos Order by Apellido", DataGridView1)
71. 72. End Sub 73. 74. Private Sub cargar_registros( _ 75. ByVal sql As String, _ 76. ByVal dv As DataGridView) 77. 78. Try
79. ' Inicializar el SqlDataAdapter indicandole el comando y el connection string
80. SqlDataAdapter = New SqlDataAdapter(sql, cs)
81. 82. Dim SqlCommandBuilder As
New SqlCommandBuilder(SqlDataAdapter) 83. 84. ' llenar el DataTable 85. Dim dt As New DataTable() 86. SqlDataAdapter.Fill(dt) 87. 88. ' Enlazar el BindingSourc
e con el datatable anterior 89. ' '''''''''''''''''''''''
''''''''''''''''''''''''''''''''''''' 90. bs.DataSource = dt 91. 92. With dv 93. .Refresh() 94. ' coloca el registro
arriba de todo 95. .FirstDisplayedScroll
ingRowIndex = bs.Position 96. End With 97. 98. bEdit = False 99. 100. Catch exSql As SqlException 101. MsgBo
x(exSql.Message.ToString) 102. Catch ex As Exception 103. MsgBo
x(ex.Message.ToString) 104. End Try 105. End Sub 106. 107. ' botón para guardar los cambios
y llenar la grilla 108. Private Sub Button1_Click( _
109. ByVal sender As System.Object, _
110. ByVal e As System.EventArgs) Handles btn_Update.Click
111. 112. Actualizar() 113. 114. End Sub 115. 116. 117. ' Eliminar el elemento actual del
BindingSource y actualizar 118. Private Sub btn_delete_Click( _ 119. ByVal sender As System
.Object, _ 120. ByVal e As System.EventArgs)
Handles btn_delete.Click 121. 122. If Not bs.Current Is Nothing
Then 123. ' eliminar 124. bs.RemoveCurrent() 125. 126. 'Guardar los cambios y re
cargar 127. Actualizar() 128. Else 129. MsgBox("No hay un registr
o actual para eliminar", _ 130. MsgBoxStyle.Exclam
ation, _ 131. "Eliminar") 132. End If 133. 134. 135. End Sub 136. 137. Private Sub Actualizar(Optional B
yVal bCargar As Boolean = True) 138. ' Actualizar y guardar cambio
s
139. 140. If Not bs.DataSource Is Nothi
ng Then 141. SqlDataAdapter.Update
(CType(bs.DataSource, DataTable)) 142. If bCargar Then 143. cargar_registros
("Select * From alumnos Order by Apellido", DataGridView1)
144. End If 145. End If 146. End Sub 147. 148. Private Sub btn_first_Click( _ 149. ByVal sender As System
.Object, _ 150. ByVal e As System.EventArgs)
_ 151. Handles btn_first.Click,
btn_last.Click, btn_next.Click, btn_Previous.Click
152. 153. ' Botones para moverse por lo
s registros 154. ' '''''''''''''''''''''''''''
'''''''''''''''''' 155. 156. If sender Is btn_Previous The
n 157. bs.MovePrevious() 158. ElseIf sender Is btn_first Th
en 159. bs.MoveFirst() 160. ElseIf sender Is btn_next The
n 161. bs.MoveNext() 162. ElseIf sender Is btn_last The
n 163. bs.MoveLast() 164. End If 165.
166. End Sub 167. 168. Private Sub DataGridView1_CellEnd
Edit( _ 169. ByVal sender As Object, _ 170. ByVal e As System.Windows.For
ms.DataGridViewCellEventArgs) _ 171. Handles DataGridView1.Cel
lEndEdit 172. 173. bEdit = True 174. End Sub 175. 176. ' nuevo registro 177. Private Sub btn_new_Click( _ 178. ByVal sender As System
.Object, _ 179. ByVal e As System.EventArgs)
Handles btn_new.Click 180. 181. bs.AddNew() 182. 183. End Sub 184. End Class