Sunteți pe pagina 1din 9

Ejemplo para actualizar y guardar realizados en un control DataGridview

cambios

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 ( para btn_delete, eliminar ,

btn_Update,

btn_new)

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 mtodos MoveFirst , MoveNext etc.. del componente Bindingsource

Establecer

la

cadena

de

conexin

la

instruccin sql para cargar la tabla en el datagridview

Cdigo fuente
Texto planoCopiar cdigo fuenteImprimir 1. Option Explicit On
2.

Option Strict On ' Espacios de nombres ' '''''''''''''''''''''''''''''''''''''' ''' Imports System.Data.SqlClient Public Class Form1 'BindingSource Private WithEvents bs As New Binding Source ' Adaptador de datos sql Private SqlDataAdapter As SqlDataAda pter

3.
4. 5. 6.

7.
8.

9.
10. 11.

12.
13. 14.

15.
16.

' Cadena de conexin

17. 18.

Private Const cs As String = "Data S ource=(local)\SQLEXPRESS;" & _ "Initia l Catalog=demo_bd;" & _ "Integr ated Security=true"

19.

20.
21. 22.

' flag Private bEdit As Boolean

23. 24.
25. 26. 27. 28. 29. 30.

' actualizar los cambios al salir ' '''''''''''''''''''''''''''''''''' '''''' Private Sub Form1_FormClosing( _ ByVal sender As Object, _ ByVal e As System.Windows.Forms. FormClosingEventArgs) _ Handles Me.FormClosing If bEdit Then 'preguntar si se desea guard ar If (MsgBox( _ "Guardar cambios ?", _ MsgBoxStyle.YesNo, _ "guardar")) = MsgBox Result.Yes Then

31.
32. 33. 34. 35. 36. 37.

38.
39. 40. 41.

Actualizar(False) End If End If

42.

End Sub Private Sub Form1_Load( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) Han dles MyBase.Load ' propiedades del datagrid ' '''''''''''''''''''''''''''''' ''''''' With DataGridView1 ' alternar color de filas

43.
44. 45. 46.

47.
48. 49. 50. 51.

52. .AlternatingRowsDefaultCell Style.BackColor = Color.FloralWhite


53. 54. 55. 56.

.DefaultCellStyle.BackColor = Color.Beige ' Establecer el origen de da tos para el DataGridview .DataSource = bs End With ' botones ' '''''''''''''''''''''''''''''' ''''''' btn_Update.Text = "Guardar cambi os" btn_delete.Text = "Eliminar regi stro" btn_new.Text = "Nuevo" btn_first.Text = "<<" btn_Previous.Text = "<" btn_next.Text = ">"

57.
58. 59. 60. 61. 62.

63.
64. 65. 66.

67.

btn_last.Text = ">>" ' cagar los datos cargar_registros("Select * From alumnos Order by Apellido", DataGridView 1) End Sub Private Sub cargar_registros( _ ByVal sql As String, _ ByVal dv As DataGridView) Try ' Inicializar el SqlDataAdap ter indicandole el comando y el connecti on string SqlDataAdapter = New SqlData Adapter(sql, cs) Dim SqlCommandBuilder As New SqlCommandBuilder(SqlDataAdapter) ' llenar el DataTable Dim dt As New DataTable() SqlDataAdapter.Fill(dt) ' Enlazar el BindingSource c on el datatable anterior ' '''''''''''''''''''''''''' '''''''''''''''''''''''''''''''''' bs.DataSource = dt

68.
69. 70.

71.
72.

73.
74. 75. 76.

77.
78. 79.

80.

81.
82.

83.
84. 85. 86.

87.
88. 89. 90.

91.

92. 93. 94.

With dv .Refresh() ' coloca el registro arr iba de todo .FirstDisplayedScrolling RowIndex = bs.Position End With bEdit = False Catch exSql As SqlException MsgBox(exSql.Message.ToStri Catch ex As Exception MsgBox(ex.Message.ToString) End Try End Sub

95. 96.

97.
98.

99.
100. 101.

ng)
102. 103. 104. 105.

106.
107. 108. 109.

' botn para guardar los cambios y llenar la grilla Private Sub Button1_Click( _ ByVal sender As System.Object,

_
110.

ByVal e As System.EventArgs) Ha ndles btn_Update.Click Actualizar() End Sub

111. 112. 113.


114.

115. 116.

117. 118. 119.

' Eliminar el elemento actual del B indingSource y actualizar Private Sub btn_delete_Click( _ ByVal sender As System.Object,

_
120.

ByVal e As System.EventArgs) Ha ndles btn_delete.Click If Not bs.Current Is Nothing Th ' eliminar bs.RemoveCurrent() 'Guardar los cambios y reca Actualizar() Else

121.
122.

en
123. 124.

125.
126.

rgar 127.
128. 129. 130.

MsgBox("No hay un registro actual para eliminar", _ MsgBoxStyle.Exclamat "Eliminar") End If ion, _

131. 132.

133. 134.
135.

End Sub

136.
137. 138.

Private Sub Actualizar(Optional ByV al bCargar As Boolean = True) ' Actualizar y guardar cambios

139.
140.

If Not bs.DataSource Is Nothing

Then

141. 142. 143.

SqlDataAdapter.Update(CType (bs.DataSource, DataTable)) If bCargar Then cargar_registros("Selec t * From alumnos Order by Apellido", Dat aGridView1) End If End If End Sub Private Sub btn_first_Click( _ ByVal sender As System.Object, ByVal e As System.EventArgs) _

144. 145. 146.

147.
148. 149.

_
150. 151.

Handles btn_first.Click, bt n_last.Click, btn_next.Click, btn_Previo us.Click ' Botones para moverse por los registros ' ''''''''''''''''''''''''''''' '''''''''''''''' If sender Is btn_Previous Then bs.MovePrevious() ElseIf sender Is btn_first Then bs.MoveFirst() ElseIf sender Is btn_next Then bs.MoveNext() ElseIf sender Is btn_last Then bs.MoveLast() End If

152.
153. 154.

155.
156. 157. 158. 159. 160. 161. 162. 163. 164.

165.
166.

End Sub

167.
168. 169. 170. 171.

Private Sub DataGridView1_CellEndEd it( _ ByVal sender As Object, _ ByVal e As System.Windows.Forms .DataGridViewCellEventArgs) _ Handles DataGridView1.CellE ndEdit

172.
173. 174.

bEdit = True End Sub ' nuevo registro Private Sub btn_new_Click( _ ByVal sender As System.Object,

175.
176. 177. 178.

_
179.

ByVal e As System.EventArgs) Ha ndles btn_new.Click bs.AddNew() End Sub Class

180.
181.

182.
183. 184.End

S-ar putea să vă placă și