
ACTUALIZAR MI BASE DE DATOS
Publicado por estiven (3 intervenciones) el 09/10/2017 02:39:48
Muy buenas noches compañero del foro.
Desde hace varios días llevo intento resolver este problema, pero no he podido.
El proyecto que estoy realizando lo saque del libro “Visual Basic guía definitiva del programador, por Omar Luna” todo iba bien hasta que llegue al frmVentas,
Este es el formulario:
La idea es que cuando se le de clic al botón agregar, los datos de la venta se envíen a la tabla Ventas que pertenece a la base de datos Drugstore.mdf, para que luego en el código desde ese mismo botón, se filtren los registro que tengan el mismo numero de venta para luego mostrármelos en el datagridview; este datagridvew tiene enlazado uno vista, la cual tiene relacionada las tablas ventas y productos.
El problema radica en que los datos se actualizan solo cuando cierro y vuelvo a ejecutar el programa, entonces al agregar otro registro con el mismo número de factura de la venta anterior (solo la deja con el mismo número de la venta anterior por motivos de diseño), me filtra los registros de la venta anterior y no la actual, después de manipular mucho el código, no he podido encontrar la solución.
Necesito lograr que los datos se me actualicen de manera inmediata a la tabla para que el filtro sea correcto.
Si alguien sabe cómo resolverlo sería de mucha ayuda.
Muchas gracias y quedo atento.
NOTA: estoy programando en Microsoft Visual Basic 2010 Express, con base de datos en SQL, Adjunto el código completo del formulario frmVentas.

Desde hace varios días llevo intento resolver este problema, pero no he podido.
El proyecto que estoy realizando lo saque del libro “Visual Basic guía definitiva del programador, por Omar Luna” todo iba bien hasta que llegue al frmVentas,
Este es el formulario:
La idea es que cuando se le de clic al botón agregar, los datos de la venta se envíen a la tabla Ventas que pertenece a la base de datos Drugstore.mdf, para que luego en el código desde ese mismo botón, se filtren los registro que tengan el mismo numero de venta para luego mostrármelos en el datagridview; este datagridvew tiene enlazado uno vista, la cual tiene relacionada las tablas ventas y productos.
El problema radica en que los datos se actualizan solo cuando cierro y vuelvo a ejecutar el programa, entonces al agregar otro registro con el mismo número de factura de la venta anterior (solo la deja con el mismo número de la venta anterior por motivos de diseño), me filtra los registros de la venta anterior y no la actual, después de manipular mucho el código, no he podido encontrar la solución.
Necesito lograr que los datos se me actualicen de manera inmediata a la tabla para que el filtro sea correcto.
Si alguien sabe cómo resolverlo sería de mucha ayuda.
Muchas gracias y quedo atento.
NOTA: estoy programando en Microsoft Visual Basic 2010 Express, con base de datos en SQL, Adjunto el código completo del formulario frmVentas.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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
80
81
82
83
84
85
86
87
88
89
90
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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
Imports System.Data.Sql
Imports System.Data.SqlClient
Imports Drugstore.drogstore
Public Class frmVentas
Dim cnString As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=C:\data bases\Drugstore\Drugstore\drugstore.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"
Private Sub Ventas_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'TODO: esta línea de código carga datos en la tabla 'DrugstoreDataSet1.Ventas' Puede moverla o quitarla según sea necesario.
Me.VentasTableAdapter.Fill(Me.DrugstoreDataSet1.Ventas)
'TODO: esta línea de código carga datos en la tabla 'DrugstoreDataSet1.Productos' Puede moverla o quitarla según sea necesario.
Me.ProductosTableAdapter.Fill(Me.DrugstoreDataSet1.Productos)
'TODO: esta línea de código carga datos en la tabla 'DrugstoreDataSet1.vw_ventas' Puede moverla o quitarla según sea necesario.
Me.Vw_ventasTableAdapter.Fill(Me.DrugstoreDataSet1.vw_ventas)
Me.VwventasBindingSource.Filter = "nroventa = 0"
btnCancelar.Enabled = False
btnGrabar.Enabled = False
lblfecha.Text = DateTime.Now.ToString("dd/MM/yyyy")
End Sub
Function graboNuevoNro() As Boolean
Dim con As New SqlConnection(cnString)
Dim sqlQ As String = "UPDATE numeracion SET numticket = (numticket + 1)"
Dim cmd As New SqlCommand(sqlQ, con)
graboNuevoNro = False
con.Open()
cmd.ExecuteNonQuery()
graboNuevoNro = True
End Function
Sub cambioBotones()
btnNuevaVenta.Enabled = Not btnNuevaVenta.Enabled
btnCancelar.Enabled = True
btnGrabar.Enabled = True
End Sub
Function traigoUltimoNro() As String
Dim dbConnection As New SqlConnection(cnString)
Dim sqlQ As String = "SELECT numticket FROM numeracion"
Dim Reader As SqlDataReader
Dim cmd As New SqlCommand(sqlQ, dbConnection)
traigoUltimoNro = -1
dbConnection.Open()
cmd.Connection = dbConnection
cmd.CommandText = sqlQ
Reader = cmd.ExecuteReader
Reader.Read()
traigoUltimoNro = FormatNumber(Reader.Item(0).ToString, 2) + 1
Reader.Close()
End Function
Private Sub btnNuevaVenta_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNuevaVenta.Click
lblVenta.Text = traigoUltimoNro()
txtSelecciono.Focus()
cambioBotones()
End Sub
Private Sub txtSelecciono_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtSelecciono.TextChanged
If Trim(txtSelecciono.Text) = "" Then
Me.ProductosBindingSource.RemoveFilter()
Me.gridProd.Visible = False
Else
Me.ProductosBindingSource.Filter = "descripcion LIKE '*" & Trim(txtSelecciono.Text) & "%'"
Me.gridProd.Visible = True
Me.gridProd.Width = 608
End If
End Sub
Private Sub btnSelecciona_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSelecciona.Click
With gridProd
If gridProd.Rows.Count = 0 Then Exit Sub
lblDesc.Tag = .CurrentRow.Cells(0).Value
lblDesc.Text = .CurrentRow.Cells(1).Value
lblStk.Text = Format(.CurrentRow.Cells(2).Value, 2)
lblImporte.Text = Format(.CurrentRow.Cells(3).Value, "c")
End With
txtSelecciono.Text = ""
txtCantidad.Focus()
End Sub
Private Sub txtCantidad_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtCantidad.TextChanged
If Trim(txtCantidad.Text) = " " Then lblSubt.Text = 0 : Exit Sub
If IsNumeric(Trim(txtCantidad.Text)) Then
lblSubt.Text = Format(CSng(txtCantidad.Text) * CSng(lblImporte.Text), "c")
End If
End Sub
Sub calculoTotal()
Dim cn As New SqlConnection(cnString)
Dim sqlQ As String = "SELECT sum(subtotal) AS Total FROM ventas WHERE nroventa = " & CSng(lblVenta.Text)
Dim cmd As New SqlCommand(sqlQ, cn)
Dim Reader As SqlDataReader
cn.Open()
cmd.Connection = cn
cmd.CommandText = sqlQ
Reader = cmd.ExecuteReader
Reader.Read()
Dim d As Double = CDbl(Reader.Item(0))
lblTotal.Text = Format(d, "c")
Reader.Close()
End Sub
Private Sub btnAgregar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAgregar.Click
Dim dbConnection As New SqlConnection(cnString)
Dim sqlInsert As String = "INSERT INTO ventas (nroventa, id, cantidad, preciounitario, subtotal,fecha) "
Dim sqlValores As String = "VALUES('" & CSng(lblVenta.Text) & "', '" & CSng(lblDesc.Tag) & "', '" & CSng(txtCantidad.Text) & "', '" & CSng(lblImporte.Text) & "', '" & CSng(lblSubt.Text) & "',' " & lblfecha.Text & "')"
Dim cmd As New SqlCommand(sqlInsert + sqlValores, dbConnection)
dbConnection.Open()
cmd.ExecuteNonQuery()
Dim conn = New SqlConnection(cnString)
Dim da = New SqlDataAdapter("Select * from ventas", conn)
Dim cmde = New SqlCommandBuilder(da)
da.UpdateCommand = cmde.GetUpdateCommand
da.Fill(DrugstoreDataSet1, "ventas")
da.Update(DrugstoreDataSet1, "ventas")
Me.Validate()
Me.VentasBindingSource.EndEdit()
Dim deletedOrders As DrugstoreDataSet1.VentasDataTable = CType(
DrugstoreDataSet1.Ventas.GetChanges(Data.DataRowState.Deleted), DrugstoreDataSet1.VentasDataTable)
Dim newOrders As DrugstoreDataSet1.VentasDataTable = CType(
DrugstoreDataSet1.Ventas.GetChanges(Data.DataRowState.Added), DrugstoreDataSet1.VentasDataTable)
Dim modifiedOrders As DrugstoreDataSet1.VentasDataTable = CType(
DrugstoreDataSet1.Ventas.GetChanges(Data.DataRowState.Modified), DrugstoreDataSet1.VentasDataTable)
consultar(VentasDataGridView)
cnString
Me.VwventasBindingSource.Filter = "nroventa = " & CSng(lblVenta.Text)
lblDesc.Text = "Descripción del producto"
lblStk.Text = "Stock actual"
lblImporte.Text = "Importe unitario"
txtCantidad.Text = ""
lblSubt.Text = "Subtotal"
calculoTotal()
Return
End Sub
Private Sub TablaVentasToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TablaVentasToolStripMenuItem.Click
Tablaventas.Show()
End Sub
Private Function run() As Object
Throw New NotImplementedException
End Function
Private Sub btnGrabar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGrabar.Click
With VentasDataGridView
.DataSource = VentasBindingSource
.Refresh()
End With
End Sub
Sub consultar(ByVal tabla As DataGridView)
Dim adaptador = New SqlDataAdapter("select* from ventas", cnString)
Dim dataS As New DataSet
adaptador.Fill(dataS, "ventas")
tabla.DataSource = dataS.Tables("ventas")
End Sub
End Class

Valora esta pregunta


0