elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: (TUTORIAL) Aprende a emular Sentinel Dongle By Yapis


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  Ayuda con datagridview
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: Ayuda con datagridview  (Leído 2,089 veces)
dark08

Desconectado Desconectado

Mensajes: 30



Ver Perfil
Ayuda con datagridview
« en: 10 Junio 2012, 04:39 am »

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

Código:





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
        Dim total As Double
        Dim cant As String
        Dim descripcion As String
        Dim preciov As String



        '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.CvproductoTextBox.Text, Me.DescripcionTextBox1.Text, Me.ArchivoTextBox.Text, Me.CostoTextBox.Text, Me.CantidadTextBox.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

        ' 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"
                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


  end sub
End Class











En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
ayuda con la programacion de un datagridview en C#
.NET (C#, VB.NET, ASP)
user_b 3 16,027 Último mensaje 30 Mayo 2007, 14:54 pm
por »~^~«CkNU!»~^~«
uso del datagridview
.NET (C#, VB.NET, ASP)
Choclito 1 4,560 Último mensaje 11 Noviembre 2010, 05:00 am
por .::IT::.
Ayuda a ocultar un dato en un DataGridView
Bases de Datos
jacj0102 3 7,489 Último mensaje 18 Junio 2011, 18:09 pm
por Novlucker
Ayuda con DataGridView
.NET (C#, VB.NET, ASP)
bitaziko 7 5,307 Último mensaje 29 Diciembre 2011, 07:39 am
por 24K
Ayuda con DataGridView y MySql
.NET (C#, VB.NET, ASP)
alexjoffre 3 8,953 Último mensaje 16 Enero 2012, 14:27 pm
por alexjoffre
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines