Ejerciciofacturas

Page 1

IMPLEMENTANDO UN PROGRAMA PARA FACTURACION 1. Entrar a ACCESS. Crear una nueva base de datos llamada VENTAS.MDB Guardarla en formato 2003 2. Crear las siguientes tablas dentro de la base de datos VENTAS.MDB

3. Seleccionar <<Relaciones>> desde el menu de ACCESS:


4. Establecer las siguientes relaciones entre las tablas

5. Introducir algunos datos de prueba en las tablas de Clientes y Productos:

6. En C#, realizar la siguiente Forma de Windows:


7. En el dataGridView, desmarcar todo y dejar solamente marcado “Enable Deleting” (Permitir borrar) en el SmartTag que aparece en la parte superior derecha del DataGridView en tiempo de diseño. 8. Colocar Nombres a los controles: (Nota: Los nombres aparecen listados en el mismo orden en el que aparecen los controles en la Forma): • • • • • • •

txtNumFactura (ReadOnly=true), dtpFecha, cmbClientes, cmbProductos, txtPrecioUnitario (ReadOnly=true), txtCantidad, txtTotalProducto (ReadOnly=true), dgvArticulos (Nota: En este DataGridView, colocar 5 columnas con los datos que aparecen en la imagen), txtSubtotal (ReadOnly=true), txtIva (ReadOnly=true), txtTotal (ReadOnly=true)

9. Guarde su proyecto. Ubique la carpeta donde se guardó. Navegue hasta la ruta: C:\...\...\bin\Debug Y copie ahí la base de datos en ACCESS llamada VENTAS.MDB 10. Coloque el código del programa:


using using using using using using using using

System; System.Collections.Generic; System.ComponentModel; System.Data; System.Drawing; System.Linq; System.Text; System.Windows.Forms;

//INCLUIR ESTA SENTENCIA using System.Data.OleDb; namespace WindowsFormsApplication1 { public partial class Form1 : Form { //A NIVEL DE LA FORMA string cc = @"Provider=Microsoft.Jet.Oledb.4.0; data source =" + Application.StartupPath +"\\ventas.mdb"; OleDbConnection cn; private void Conectar() { cn = new OleDbConnection(cc); cn.Open(); } private DataTable EjecutarComando(string comando) { OleDbCommand com = new OleDbCommand(comando, cn); OleDbDataReader dr = com.ExecuteReader(); DataTable dt = new DataTable(); dt.Load(dr); return dt; } private void CargarClientes() { DataTable dt = EjecutarComando("select * from clientes"); cmbClientes.DataSource = dt; cmbClientes.DisplayMember = "Nombre"; cmbClientes.ValueMember = "Clave"; } private void CargarArticulos() { DataTable dt = EjecutarComando("select * from productos order by descripcion"); cmbProductos.DataSource = dt; cmbProductos.DisplayMember = "Descripcion"; cmbProductos.ValueMember = "Clave"; cmbProductos.SelectedIndex = -1; } private void ActualizarTotales() { double sub = 0; for (int x = 0; x < dgvArticulos.Rows.Count; x++) { sub += Convert.ToDouble(dgvArticulos[4, x].Value); } double iva = sub *0.11; double tot = sub + iva; txtSubtotal.Text = sub.ToString("c2"); txtIva.Text = iva.ToString("c2"); txtTotal.Text = tot.ToString("c2"); }


private void LimpiarControles() { txtNumFactura.Text = ""; cmbClientes.SelectedIndex = -1; cmbProductos.SelectedIndex = -1; dtpFecha.Value = DateTime.Today; dgvArticulos.Rows.Clear(); txtPrecioUnitario.Text = ""; txtCantidad.Text = ""; txtTotalProducto.Text = ""; txtSubtotal.Text = ""; txtTotal.Text = ""; txtIva.Text = ""; } private void Form1_Load(object sender, EventArgs e) { //AL CARGAR LA FORMA Conectar(); CargarClientes(); CargarArticulos(); } private void cmbProductos_SelectedIndexChanged(object sender, EventArgs e) { //AL CAMBIAR EL SELECTEDINDEX DEL CMBPRODUCTOS try { DataTable dt = (DataTable)cmbProductos.DataSource; if (dt.Rows.Count > 0) { int clave = (int)cmbProductos.SelectedValue; DataRow[] drs = dt.Select("Clave =" + clave); DataRow dr = drs[0]; double precio = Convert.ToDouble(dr["PrecioUnitario"]); txtPrecioUnitario.Text = precio.ToString(); txtCantidad.Focus(); } } catch { } }

private void txtCantidad_Leave(object sender, EventArgs e) { //EN EL EVENTO LEAVE DE TXTCANTIDAD //(Cuando el cursor deja de estar en el textBox if (txtCantidad.Text.Trim() == "") { MessageBox.Show("Debe teclear una cantidad!"); } else { double tot = double.Parse(txtPrecioUnitario.Text) * double.Parse(txtCantidad.Text); txtTotalProducto.Text = tot.ToString(); } }


private void button2_Click_1(object sender, EventArgs e) { //BOTON AGREGAR if (cmbProductos.SelectedValue != null && txtCantidad.Text.Trim() != "" && txtPrecioUnitario.Text != "" && txtTotalProducto.Text != "") { DataRowView drv = (DataRowView)cmbProductos.SelectedItem; dgvArticulos.Rows.Add(drv["Clave"].ToString(), drv["Descripcion"].ToString(), txtPrecioUnitario.Text, txtCantidad.Text, txtTotalProducto.Text); ActualizarTotales(); } else { MessageBox.Show("No puede agregar. Faltan datos"); } } private void button1_Click(object sender, EventArgs e) { //BOTON FINALIZAR LA COMPRA DataTable dt = EjecutarComando("Select Max(NumFactura) from RenglonesFactura"); int numFactura=0; int claveCliente = Convert.ToInt32(cmbClientes.SelectedValue); DateTime fecha = dtpFecha.Value; if (dt.Rows[0].IsNull(0)==false) { numFactura = Convert.ToInt32(dt.Rows[0][0]); } numFactura++; string comando = string.Format("INSERT INTO FACTURAS (NumFactura, ClaveCliente, Fecha) VALUES ({0}, {1}, #{2}#)", numFactura, claveCliente, fecha); EjecutarComando(comando); for (int x = 0; x < dgvArticulos.Rows.Count; x++) { string claveProd= dgvArticulos[0,x].Value.ToString(); string pU = dgvArticulos[2,x].Value.ToString(); string cant = dgvArticulos[3,x].Value.ToString(); comando = string.Format("INSERT INTO RENGLONESFACTURA (NumFactura,Renglon, ClaveProducto,PrecioUnitario,Cantidad) VALUES ({0},{1},{2},{3},{4})", numFactura,x+1,claveProd,pU,cant); EjecutarComando(comando); comando = string.Format("UPDATE PRODUCTOS SET EXISTENCIAS = EXISTENCIAS - {0} WHERE CLAVE = {1}", cant, claveProd); EjecutarComando(comando); } txtNumFactura.Text = numFactura.ToString(); MessageBox.Show("Factura guardada Num. " + numFactura); LimpiarControles(); } private void dgvArticulos_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e) { //EVENTO ROWSREMOVED DEL DATAGRIDVIEW ActualizarTotales(); } } }


Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.