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
Cdigo fuente Texto planoImprimir 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. ' funcin 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_Colu mna" 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. ' aadir 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. ' aadir 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 mtodos MoveFirst , MoveNext etc.. del componente Bindingsource Establecer la cadena de conexin y la instruccin sql para cargar la tabla en el datagridview
Cdigo fuente
Texto planoImprimir 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 conexin 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. 47. 48. 49. 50. 51. 52. 53. 54. 55. 56. 57. 58. 59. 60. 61. 62. 63. 64. 65. 66. 67. 68. 69. 70. 71. 72. 73. 74. 75. 76. 77. 78. 79. g 80. 81. 82. 83. 84. 85. 86. 87. 88. 89. 90.
ByVal e As System.EventArgs) Handles MyBase.Load ' propiedades del datagrid ' ''''''''''''''''''''''''''''''''''''' With DataGridView1 ' alternar color de filas .AlternatingRowsDefaultCellStyle.BackColor = Color.FloralWhite .DefaultCellStyle.BackColor = Color.Beige ' Establecer el origen de datos para el DataGridview .DataSource = bs End With ' botones ' ''''''''''''''''''''''''''''''''''''' btn_Update.Text = "Guardar cambios" btn_delete.Text = "Eliminar registro" btn_new.Text = "Nuevo" btn_first.Text = "<<" btn_Previous.Text = "<" btn_next.Text = ">" btn_last.Text = ">>" ' cagar los datos cargar_registros("Select * From alumnos Order by Apellido", DataGridView1)
End Sub Private Sub cargar_registros( _ ByVal sql As String, _ ByVal dv As DataGridView) Try ' Inicializar el SqlDataAdapter indicandole el comando y el connection strin SqlDataAdapter = New SqlDataAdapter(sql, cs) Dim SqlCommandBuilder As New SqlCommandBuilder(SqlDataAdapter) ' llenar el DataTable Dim dt As New DataTable() SqlDataAdapter.Fill(dt) ' Enlazar el BindingSource con el datatable anterior ' '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' bs.DataSource = dt
91. 92. 93. 94. 95. 96. 97. 98. 99. 100. 101. 102. 103. 104. 105. 106. 107. 108. 109. 110. 111. 112. 113. 114. 115. 116. 117. 118. 119. 120. 121. 122. 123. 124. 125. 126. 127. 128. 129. 130. 131. 132. 133. 134. 135. 136. 137.
With dv .Refresh() ' coloca el registro arriba de todo .FirstDisplayedScrollingRowIndex = bs.Position End With bEdit = False Catch exSql As SqlException MsgBox(exSql.Message.ToString) Catch ex As Exception MsgBox(ex.Message.ToString) End Try End Sub ' botn para guardar los cambios y llenar la grilla Private Sub Button1_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btn_Update.Click Actualizar() End Sub
' Eliminar el elemento actual del BindingSource y actualizar Private Sub btn_delete_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btn_delete.Click If Not bs.Current Is Nothing Then ' eliminar bs.RemoveCurrent() 'Guardar los cambios y recargar Actualizar() Else MsgBox("No hay un registro actual para eliminar", _ MsgBoxStyle.Exclamation, _ "Eliminar") End If
End Sub 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. 184.
End Sub End Class
Agregar combo a una grid
Imports System.Data.SqlClient Public 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 Sub End Class