Upload
luis-hernandez
View
1.571
Download
0
Tags:
Embed Size (px)
Citation preview
Sencillo ejemplo en vb.net para sumar una columna determinada en un control DataGridview
Para el ejemplo colocar en un formulario dos controles Button, un control Label y un Datagridview
Código fuente
Texto plano Imprimir
1. Option Explicit On 2. Option Strict On 3. 4. Public Class Form1 5. 6. Private Sub Form1_Load( _ 7. ByVal sender As System.Object, _ 8. ByVal e As System.EventArgs) Handles MyBase.Load 9. Me.Text = "Sumar columnas en DataGridview" 10. Button1.Text = "Sumar" 11. Button2.Text = "Cargar valores" 12. End Sub 13. 14. ' función que retorna el total 15. Private Function Sumar( _ 16. ByVal nombre_Columna As String, _ 17. ByVal Dgv As DataGridView) As Double 18. 19. Dim total As Double = 0 20.
21. ' recorrer las filas y obtener los items de la columna indicada en "nombre_Columna"
22. Try 23. For i As Integer = 0 To Dgv.RowCount - 1 24. total = total + CDbl(Dgv.Item(nombre_Columna.ToLower, i).Value) 25. Next 26. 27. Catch ex As Exception 28. MsgBox(ex.Message.ToString) 29. End Try 30. 31. ' retornar el valor 32. Return total 33. 34. End Function 35. 36. Private Sub Button1_Click( _ 37. ByVal sender As System.Object, _ 38. ByVal e As System.EventArgs) Handles Button1.Click 39. 40. ' muostrar el total de la suma en el control Label para la columna llamada Cost
o 41. Label1.Text = "Total :" & Format(Sumar("costo", DataGridView1), "c").ToStr
ing 42. End Sub 43. 44. Private Sub Button2_Click( _ 45. ByVal sender As System.Object, _ 46. ByVal e As System.EventArgs) Handles Button2.Click 47. 48. Randomize() 49. 50. With DataGridView1 51. ' Agregar dos columnas 52. .Columns.Clear() 53. .Columns.Add("Id", "Id Producto") 54. .Columns.Add("Costo", "Costo") 55. ' agregar 10 filas 56. .RowCount = 10 57. 58. ' añadir un valor para el campo ID 59. For Filas As Integer = 0 To .RowCount - 1 60. .Item(0, Filas).Value = Filas 61. Next 62. 63. ' añadir un valor aleatorio para el campo Costo 64. For Filas As Integer = 0 To .RowCount - 1
65. .Item(1, Filas).Value = Format(CInt(Rnd() * 2500), "c") 66. Next 67. End With 68. End Sub 69. End Class
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 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 BindingSource 12. 13. ' Adaptador de datos sql 14. Private SqlDataAdapter As SqlDataAdapter 15. 16. ' Cadena de conexión 17. Private Const cs As String = "Data 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.Forms.FormClosingEventArgs) _ 30. Handles Me.FormClosing 31. 32. If bEdit Then 33. 'preguntar si se desea guardar 34. If (MsgBox( _ 35. "Guardar cambios ?", _ 36. MsgBoxStyle.YesNo, _ 37. "guardar")) = MsgBoxResult.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. .AlternatingRowsDefaultCellStyle.BackColor = Color.FloralWhite 53. .DefaultCellStyle.BackColor = 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 cambios" 61. btn_delete.Text = "Eliminar registro" 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 * From 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 strin
g 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 BindingSource con el datatable anterior 89. ' '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' 90. bs.DataSource = dt
91. 92. With dv 93. .Refresh() 94. ' coloca el registro arriba de todo 95. .FirstDisplayedScrollingRowIndex = bs.Position 96. End With 97. 98. bEdit = False 99. 100. Catch exSql As SqlException 101. MsgBox(exSql.Message.ToString) 102. Catch ex As Exception 103. MsgBox(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 recargar 127. Actualizar() 128. Else 129. MsgBox("No hay un registro actual para eliminar", _ 130. MsgBoxStyle.Exclamation, _ 131. "Eliminar") 132. End If 133. 134. 135. End Sub 136. 137. Private Sub Actualizar(Optional ByVal bCargar As Boolean = True)
138. ' Actualizar y guardar cambios 139. 140. If Not bs.DataSource Is Nothing Then 141. SqlDataAdapter.Update(CType(bs.DataSource, DataTable)) 142. If bCargar Then 143. cargar_registros("Select * From alumnos Order by Apellido", Data
GridView1) 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 los registros 154. ' ''''''''''''''''''''''''''''''''''''''''''''' 155. 156. If sender Is btn_Previous Then 157. bs.MovePrevious() 158. ElseIf sender Is btn_first Then 159. bs.MoveFirst() 160. ElseIf sender Is btn_next Then 161. bs.MoveNext() 162. ElseIf sender Is btn_last Then 163. bs.MoveLast() 164. End If 165. 166. End Sub 167. 168. Private Sub DataGridView1_CellEndEdit( _ 169. ByVal sender As Object, _ 170. ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) _ 171. Handles DataGridView1.CellEndEdit 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
Agregar combo a una gridImports System.Data.SqlClientPublic Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click DataGridView1.ColumnCount = 3 DataGridView1.Columns(0).Name = "Product ID" DataGridView1.Columns(1).Name = "Product Name" DataGridView1.Columns(2).Name = "Product_Price"
Dim row As String() = New String() {"1", "Product 1", "1000"} DataGridView1.Rows.Add(row) row = New String() {"2", "Product 2", "2000"} DataGridView1.Rows.Add(row) row = New String() {"3", "Product 3", "3000"} DataGridView1.Rows.Add(row) row = New String() {"4", "Product 4", "4000"} DataGridView1.Rows.Add(row)
Dim cmb As New DataGridViewComboBoxColumn() cmb.HeaderText = "Select Data" cmb.Name = "cmb" cmb.MaxDropDownItems = 4 cmb.Items.Add("True") cmb.Items.Add("False") DataGridView1.Columns.Add(cmb)
End SubEnd Class