Visual Basic.NET - executenonquery requiere una connection abierta y disponible. el estado actual de la conexión...

 
Vista:

executenonquery requiere una connection abierta y disponible. el estado actual de la conexión...

Publicado por Jose Luis (1 intervención) el 10/06/2012 03:20:08
Hola, tengo un problema con una base de datos y mi interface, esta tiene que realizar una venta, explicandolo mejor:

-una tabla ventas que tiene actualizar el total cuando se inserten los datos en pv osea cantidad y precio, esto pasa cuando yo agrego la informacion con un triger esto esta resuelto
-tengo una tabla pv
-tengo una tabla productos que disminuyen las existencias cuando inserto en pv la cantidad mediante un triger.

Tengo este error; executenonquery requiere una connection abierta y disponible. el estado actual de la conexión es cerrada, creo que es por la conexion, pero no se como solucionarlo.

En mi base de datos, se tiene que preparar una venta, para ello primero busco mediante la clave de la venta cual es la mayor, y depende a ella le sumo otra mas (no se si este bien ahi), sucesivamente puedo mandar a traer un procediemiento almacenado para que ejecute los trigers y sumen total y bajen existencias en las sucesivas tablas, pero hice por ahi un insert tambien.
Podria alguien ayudarme, soy nuevo en esto gracias.

Anexo mi codigo

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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
Imports System.Data.SqlClient
Imports System.Data
 
Public Class Form1
    Public objBD As New clasBD()
 
    Private Con As SqlConnection
    Private sql As String
    Private Da As SqlDataAdapter
    Private Cmd As SqlCommand
 
    Public Connection As New SqlConnection("Data Source=localhost;Initial Catalog=BdRhema;Persist Security Info=True;User ID=sa;Password=bdd")
 
 
 
 
    Private res As Double
    Private Sub Form1_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 'BdRhemaDataSet.pv' Puede moverla o quitarla según sea necesario.
        Me.PvTableAdapter.Fill(Me.BdRhemaDataSet.pv)
        'TODO: esta línea de código carga datos en la tabla 'BdRhemaDataSet.productos' Puede moverla o quitarla según sea necesario.
        Me.ProductosTableAdapter.Fill(Me.BdRhemaDataSet.productos)
 
 
        Me.DescripcionTextBox1.Text = ""
        Me.ArchivoTextBox.Text = ""
        Me.CantidadTextBox.Text = ""
        Me.CvventaTextBox.Text = ""
 
 
 
    End Sub
    Private Sub btnpagar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnpagar.Click
        'res = txtcantidad.Text * CostoTextBox.Text
        'lbltotal.Text = "$ " + res.ToString
 
        'sql = "SELECT MAX(cvventa)+1 AS 'cvv' FROM ventas"
        'Da = New SqlDataAdapter(sql, Con)
        'Da.Fill(DatSet)
        'If DatSet.Tables(0).Rows.Count > 0 Then
        '    cvventa = DatSet.Tables(0).Rows(0).Item("cvv")
        'End If
 
        'sql = "ventas_insertar " + cvventa.ToString + ",2211"
        'Cmd = New SqlCommand(sql, Con)
        'Cmd.ExecuteNonQuery()
 
    End Sub
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        End
    End Sub
    Private Sub NombreLabel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    End Sub
    Private Sub btnAgregar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAgregar.Click
        If Me.DescripcionTextBox1.Text <> "" Then
            If Me.ArchivoTextBox.Text <> "" Then
                If Me.CostoTextBox.Text <> "" Then
                    If Me.CantidadTextBox.Text <> "" Then
                        If Me.CvventaTextBox.Text <> "" Then
                        End If
                    End If
                    'agregamos la informacion a un row o fila del datagrid
                    Me.DataGridView2.Rows.Add(Me.DescripcionTextBox1.Text, Me.ArchivoTextBox.Text, Me.CostoTextBox.Text, Me.CantidadTextBox.Text, Me.CvproductoTextBox.Text, Me.CvventaTextBox.Text)
                    'limpiamos los controles
                    Me.DescripcionTextBox1.Text = ""
                    Me.ArchivoTextBox.Text = ""
                    Me.CantidadTextBox.Text = ""
                    Me.CvventaTextBox.Text = ""
                End If
            Else
                MessageBox.Show("Ingres bien el producto PLEASE", "", MessageBoxButtons.OK, MessageBoxIcon.Information)
            End If
        End If
 
    End Sub
 
    Private Sub DataGridView_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView2.CellContentClick
 
        'se puede hacer referencia al nombre de la columna para saber donde hicieron click o solo con el e.columnindex sabiendo la posicion de la columna
        'yo lo manejo asi por que se daran cuenta que en algun caso las columnas pueden aumentar o disminuir 
        'y se complicaria la cosa por que si cambia el numero de columnas habria que corregir siembre el indice
 
        'si hicieron clic en la columna eliminar
        If DataGridView2.Columns(e.ColumnIndex).Name = "Eliminar" Then
            'eliminar row
            DataGridView2.Rows.RemoveAt(e.RowIndex)
        End If
    End Sub
    Private Sub btnGuardar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnguardar.Click
 
        Dim DatSet As New DataSet
        Dim cvventa As Integer
 
        If DataGridView2.Rows.Count > 0 Then
 
            Dim SqlString As String = "" ' variable a la que asignaremos la sentencia
            Dim ListSqlStrings As New ArrayList  'arregla donde ingresaremos las sentencias
            'recorremos el datagrid como ya sabemos siempre se toma desde cero
            For i As Integer = 0 To DataGridView2.Rows.Count - 1
                'creamos la sentencia el row siempre tendra el valor de i para ir pasando de row en row
                'el campo .cells(0) indica la columna que esta ese dato, tambien puede hacerlo con el nombre de la celda .cells("Nombre")
 
 
                sql = "SELECT MAX(cvventa)+1 AS 'cvv' FROM ventas" 'aqui no se si estoy bien
                Da = New SqlDataAdapter(sql, Connection)
                'Da.Fill(DatSet)
                'If DataGridView2.Rows.Count > 0 Then
                '    cvventa = DataGridView2.Rows(0).Cells("cvv").ToString
                'End If
 
                'sql = "ventas_insertar " + cvventa.ToString + ""
                'Cmd = New SqlCommand(sql, Connection)
                'Cmd.ExecuteNonQuery()
 
                SqlString = "INSERT pv (descripcion, archivo, precio, cantidad, cvproducto, cvventa) VALUES  ('" + DataGridView2.Rows(i).Cells(0).Value.ToString + "','" + DataGridView2.Rows(i).Cells(1).Value.ToString + "','" + DataGridView2.Rows(i).Cells(2).Value.ToString + "','" + DataGridView2.Rows(i).Cells(3).Value.ToString + "','" + DataGridView2.Rows(i).Cells(4).Value.ToString + "','" + cvventa.ToString + "')"
                '" + DataGridView2.Rows(i).Cells(0).Value.ToString + "," + DataGridView2.Rows(i).Cells(1).Value.ToString + "," + DataGridView2.Rows(i).Cells(2).Value.ToString + "," + DataGridView2.Rows(i).Cells(3).Value.ToString + "," + DataGridView2.Rows(i).Cells(4).Value.ToString + "," + DataGridView2.Rows(i).Cells(5).Value.ToString + ""
 
                'agregamos la sentencia a la lista
                ListSqlStrings.Add(SqlString)
            Next
            If EjecutarTransaccion(ListSqlStrings) Then
                MessageBox.Show("Info. guardada correctamente")
                'Close()
            Else
                MessageBox.Show("La Info. no se guardo")
            End If
        Else
            MessageBox.Show("No hay informacion para guardar")
        End If
 
 
        'res = PrecioTextBox.Text * CantidadTextBox.Text
        'lbltotal.Text = "$ " + res.ToString
 
 
    End Sub
 
 
 
 
 
    'abre la conexion
 
    Public Function AbrirConexion() As Boolean
        Dim band As Boolean = False
        Try
            Connection.Open()
            band = True
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
        Return band
    End Function
 
    'cierra la conexion
    Public Function CerrarConexion() As Boolean
        Dim band As Boolean = False
        Try
            Connection.Close()
            band = True
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
        Return band
    End Function
 
    Public Function EjecutarTransaccion(ByVal ListaSentencias As ArrayList) As Boolean
        Dim band As Boolean = False
        If AbrirConexion() Then
            Dim command As SqlCommand = Connection.CreateCommand()
            Dim transaction As SqlTransaction
            Dim strSentencia As Object
            Dim sentencia As String = ""
            transaction = Connection.BeginTransaction()
            command.Connection = Connection
            command.Transaction = transaction
            Try
                For Each strSentencia In ListaSentencias
                    sentencia = strSentencia.ToString()
                    command.CommandText = sentencia.ToString()
                    command.ExecuteNonQuery()
                Next
                transaction.Commit()
                band = True
            Catch ex As Exception
                MessageBox.Show(ex.Message)
                Try
                    transaction.Rollback()
                Catch ex2 As Exception
                    MessageBox.Show(ex2.Message)
                End Try
            Finally
                CerrarConexion()
            End Try
        End If
        Return band
    End Function
 
 
    Private Sub DataGridView2_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView2.CellContentClick
 
    End Sub
 
    Private Sub DataGridView1_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
 
    End Sub
 
    Private Sub lbltimer_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lbltimer.Click
 
    End Sub
 
    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
 
    End Sub
End Class
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder

executenonquery requiere una connection abierta y disponible. el estado actual de la conexión...

Publicado por HammeR (4 intervenciones) el 13/06/2012 09:41:06
Exactamente cuando obtienes ese error? al precionar algun boton que realiza alguna operacion? o simplemente al correr tu aplicacion?,

executenonquery requiere una connection abierta y disponible. el estado actual de la conexión es cerrada

Significa que no has abierto la conexión antes de ejecutar tu consulta y creo que tu error esta en el btnPagar
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

executenonquery requiere una connection abierta y disponible. el estado actual de la conexión...

Publicado por jorge (1 intervención) el 19/09/2013 17:56:21
debes declarar una conexcion en tu public class
este es el codigo

Dim CN As New OleDbConnection("Provider=microsoft.ace.oledb.12.0;Data source=")
y en tu boton pagar pones
CN.open()
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
1
Comentar
sin imagen de perfil

executenonquery requiere una connection abierta y disponible. el estado actual de la conexión...

Publicado por Fco Javier S (4 intervenciones) el 21/09/2013 03:48:46
un consejo..
Al declarar la variable de tipo coneccion "cn" en publica ,, nunca la cierres al terminar un procedimiento,, no hasta que cierres el programa por completo
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
1
Comentar