lunes, 8 de enero de 2018

 

Boleta de venta En c# csharp Visual estudio 2017 y sql server 2020

Hola muchachos como están. Bien me imagino. Pero bueno en este post les compartiré mi código de como hacer una boleta de venta en c# con base de datos sql server 2019.

1.-Primero creamos nuestro base de datos .   TABLA boleta y detalle de boleta relacionadas respectivamente.

create database [CMFARMA]

USE [CMFARMA]
GO

/****** Object:  Table [dbo].[Boleta]    Script Date: 08/01/2018 10:01:22 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[Boleta](
       [Num_boleta] [char](14) NOT NULL,
       [fecha] [datetime] NULL,
       [cod_cli] [int] NULL,
       [cod_usu] [int] NULL,
       [Sub_total] [decimal](10, 2) NULL,
       [Descuento] [decimal](10, 2) NULL,
       [Total] [decimal](10, 2) NULL,
       [NOP] [char](14) NULL,
PRIMARY KEY CLUSTERED
(
       [Num_boleta] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

ALTER TABLE [dbo].[Boleta]  WITH CHECK ADD  CONSTRAINT [FK_Boleta_Cliente] FOREIGN KEY([cod_cli])
REFERENCES [dbo].[Cliente] ([Cod_cli])
GO

ALTER TABLE [dbo].[Boleta] CHECK CONSTRAINT [FK_Boleta_Cliente]
GO

ALTER TABLE [dbo].[Boleta]  WITH CHECK ADD  CONSTRAINT [FK_Boleta_Usuario] FOREIGN KEY([cod_usu])
REFERENCES [dbo].[Usuario] ([cod_usu])
GO

ALTER TABLE [dbo].[Boleta] CHECK CONSTRAINT [FK_Boleta_Usuario]
GO


 /****** Tabla detalle de boleta ******/


USE [CMFARMA]
GO

/****** Object:  Table [dbo].[Detalle_Boleta]    Script Date: 08/01/2018 10:04:47 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[Detalle_Boleta](
       [Num_boleta] [char](14) NULL,
       [cod_prod] [int] NULL,
       [cantidad] [char](4) NULL,
       [Precio_venta] [decimal](10, 2) NULL,
       [Importe] [decimal](10, 2) NULL
) ON [PRIMARY]
GO

ALTER TABLE [dbo].[Detalle_Boleta]  WITH CHECK ADD  CONSTRAINT [FK_Detalle_Boleta_Boleta] FOREIGN KEY([Num_boleta])
REFERENCES [dbo].[Boleta] ([Num_boleta])
GO

ALTER TABLE [dbo].[Detalle_Boleta] CHECK CONSTRAINT [FK_Detalle_Boleta_Boleta]
GO

ALTER TABLE [dbo].[Detalle_Boleta]  WITH CHECK ADD  CONSTRAINT [FK_Detalle_Boleta_Productos] FOREIGN KEY([cod_prod])
REFERENCES [dbo].[Productos] ([Cod_prod])
GO

ALTER TABLE [dbo].[Detalle_Boleta] CHECK CONSTRAINT [FK_Detalle_Boleta_Productos]
GO


 Ejecuta todo los scripts. y tendrás base de datos creados..

2.- Diseñamos nuestro formulario como en la imagen.

Codigo Fuente de  formulario.

importamos las libreria a utilizar.

using System.Data;
using System.Data.SqlClient;

--código para control Timer..

private void timer1_Tick(object sender, EventArgs e)
        {
            Label9.Text = DateTime.Now.ToString();
            label21.Text = DateTime.Now.ToShortTimeString();
        }

--load

private void timer1_Tick(object sender, EventArgs e)
        {
            Label9.Text = DateTime.Now.ToString();
            label21.Text = DateTime.Now.ToShortTimeString();
        }

 --codigo para generar numero de boleta
void generarCodigo()
        {

            DataTable dt = new DataTable();
            SqlDataAdapter da = new SqlDataAdapter("GenerarCodigo", cn.obtenerConeccion());
            da.SelectCommand.CommandType = CommandType.StoredProcedure;
            da.Fill(dt);
            if (dt.Rows.Count > 0)
            {

                DataRow row = dt.Rows[0];

                Label8.Text = Convert.ToString(row[0]);
            } 

        }

--codigo para button buscar cliente

private void BtnExaminar_Click(object sender, EventArgs e)
        {
            try
            {
                SqlCommand cm = new SqlCommand("select*from cliente where Dni='" + TextBox5.Text + "'", cn.obtenerConeccion());
                SqlDataReader dr = cm.ExecuteReader();
                if (dr.Read() == true)
                {
                    TextBox4.Text = dr["nombres"].ToString();
                    Label10.Text = dr["cod_cli"].ToString();
                    // textBox6ext = dr["Stock"].ToString();
                    textBox1.Focus();
                }
                else
                {
                    MessageBox.Show("Cliente no Encontrado", "Sistema", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    TextBox5.Text = "";
                    TextBox5.Focus();

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                cn.DescargarConexion();
            }
        }

--código para button Agregar a listview  los productos

private void btnbuscarproducto_Click(object sender, EventArgs e)
        {

            //maskedTextBox1.Text = "0";
            if (maskedTextBox1.Text == "")

            {
                MessageBox.Show("La Cantidad debe ser menor o igual al Stock", "Sistema", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                maskedTextBox1.Focus();
            }

            else if (int.Parse(maskedTextBox1.Text) > int.Parse(textBox6.Text))
            {
                //MessageBox.Show("Debes Ingresar la cantidad", "Sistema", MessageBoxButtons.OK, MessageBoxIcon.Information);
                MessageBox.Show("La cantidad supera el stock", "Sistema", MessageBoxButtons.OK, MessageBoxIcon.Error);
                maskedTextBox1.Text = "";
                maskedTextBox1.Focus();
                textBox2.Text = "";
                label26.Text = "";
                textBox3.Text = "";
                textBox6.Text = "";

            } 

            //codigo con listview

             else
            {

                Decimal precio = Decimal.Parse(textBox3.Text);
                Decimal cantidad = Decimal.Parse(maskedTextBox1.Text);
                Decimal total = (precio * cantidad);
                ListViewItem lista = new ListViewItem(label26.Text);
                lista.SubItems.Add(textBox2.Text);
                lista.SubItems.Add(textBox3.Text);
                lista.SubItems.Add(maskedTextBox1.Text);
                lista.SubItems.Add((Decimal.Parse(maskedTextBox1.Text) * Decimal.Parse(textBox3.Text)).ToString());
                listView1.Items.Add(lista);
                Decimal dblSuma = 0;

                foreach (ListViewItem item in listView1.Items)
                {
                    dblSuma += Convert.ToDecimal(item.SubItems[4].Text);
                }
                LblSub.Text = string.Format(Convert.ToString(dblSuma));
                lbltotal.Text = string.Format(Convert.ToString(dblSuma));

                //LblSub.Text = dblSuma;
                //limpia para nuevo producto
                textBox1.Text = "";
                textBox2.Text = "";
                maskedTextBox1.Text = "";
                textBox3.Text = "";
                textBox6.Text = "";
                textBox1.Focus();
                label26.Text = "";

            }

        }
---codigo para buscar producto--
private void button4_Click(object sender, EventArgs e)
        {
            SqlCommand cm = new SqlCommand("select*from productos where codigo_baras='" + textBox1.Text + "'", cn.obtenerConeccion());
            SqlDataReader dr = cm.ExecuteReader();
            if (dr.Read() == true)
            {
                label26.Text = dr["cod_prod"].ToString();
                textBox2.Text = dr["Descripcion"].ToString();
                textBox3.Text = dr["Precio_Venta"].ToString();
                textBox6.Text = dr["stock"].ToString();
              
                maskedTextBox1.Text = "";
                maskedTextBox1.Focus();
            }
            else
            {
                MessageBox.Show("Producto no Encontrado", "Sistema", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                textBox1.Text = "";
                textBox1.Focus();
            }
        }

----código para guardar boleta ala base de datos
   private void btnguardar_Click(object sender, EventArgs e)
        {
            if (TextBox5.Text == "")
            {
                MessageBox.Show("Ingrese el cliente");
                TextBox5.Text = "";
                TextBox5.Focus();
            }
            else
            {

                try
                {
                    SqlCommand cmd = new SqlCommand("guardarBoleta", cn.obtenerConeccion());
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add("@NumBoleta", SqlDbType.Char);
                    cmd.Parameters.Add("@Fecha", SqlDbType.DateTime);
                    cmd.Parameters.Add("@cod_cli", SqlDbType.Int);
                    cmd.Parameters.Add("@cod_usu", SqlDbType.Int);
                    cmd.Parameters.Add("@Subtotal", SqlDbType.Decimal);
                    cmd.Parameters.Add("@descuento", SqlDbType.Decimal);
                    cmd.Parameters.Add("@Total", SqlDbType.Decimal);
                    cmd.Parameters.Add("@NOP", SqlDbType.Decimal);
                    //asignamos el valor de los textbox a los parametros



                    cmd.Parameters["@NumBoleta"].Value = Label8.Text;
                    cmd.Parameters["@Fecha"].Value = Label9.Text;
                    cmd.Parameters["@cod_cli"].Value = Label10.Text;
                    cmd.Parameters["@cod_usu"].Value = "2";
                    cmd.Parameters["@Subtotal"].Value = LblSub.Text;
                    cmd.Parameters["@descuento"].Value = "0.00";
                    cmd.Parameters["@Total"].Value = lbltotal.Text;
                    cmd.Parameters["@NOP"].Value = "0.00";
                    //abrimos conexion
                    cn.obtenerConeccion();
                    //ejecutamos la instruccion con ExcecuteNonQuerry indicando que no retorna registros.
                    cmd.ExecuteNonQuery();
                    cn.DescargarConexion();
                    MessageBox.Show("Boleta Guardada Correctamente", "Sistema", MessageBoxButtons.OK, MessageBoxIcon.Information);

                   guardaDetalleListview();
                    listView1.Items.RemoveAt(0);
                    nuevo();
                }

                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    cn.DescargarConexion();
                }
            }

        }
        void guardaDetalleListview()
        {
            char idproducto;
                decimal cantidad, precioventa, importe;
            SqlCommand cmd = new SqlCommand("guarda_detalle_boleta", cn.obtenerConeccion());
            cmd.CommandType = CommandType.StoredProcedure;
            cn.obtenerConeccion();

            foreach (ListViewItem item in listView1.Items)
            {
                idproducto = Convert.ToChar(item.SubItems[0].Text);
                cantidad = Convert.ToDecimal(item.SubItems[3].Text);
                precioventa = Convert.ToDecimal(item.SubItems[2].Text);
                importe = Convert.ToDecimal(item.SubItems[4].Text);

                cmd.Parameters.Clear();
                cmd.Parameters.AddWithValue("@num_boleta", SqlDbType.Int).Value = Label8.Text;
                cmd.Parameters.AddWithValue("@cod_pro", idproducto);
                cmd.Parameters.AddWithValue("@cantidad", cantidad);
                cmd.Parameters.AddWithValue("@Precio_Venta", precioventa);
                cmd.Parameters.AddWithValue("@importe", importe);

                cmd.ExecuteNonQuery();


            }
            MessageBox.Show("Detalle guardado corectamente", "Sistema");

        }

Si desean adquirir el sistema completo . visita nuestro web. https://www.cpiprodesign.com/


Bueno eso seria todo..nos faltara de limpiar los controles eso les dejo a ustedes..
Saludos espero haber ayudado.Dudas y sugerencias déjanos tu mensaje en los comentarios 




Share: