Diseño Sistema de Ventas C# - Visual Studio 2013 y Sql Server 2014 (35-41) Gestión Ventas
Buen día amigos, en este post continuaremos programando las funcionalidades en el formulario FrmVenta de la capa Presentación, este formulario permitirá al usuario del sistema realizar las ventas; el usuario seleccionará aquí el cliente del negocio que participa en la venta, seleccionará el tipo de documento e ingresará un número de documento; podrá agregar uno o varios artículos por venta a un listado que luego serán almacenados en la base de datos teniendo en cuenta la cantidad de venta del artículo, el precio de Venta, y el descuento.
Pueden descargar el paquete del proyecto desarrollado en el curso, la base de datos, los procedimientos almacenados y el sistema completo hasta el Video 41 desde:
Puedes descargar la versión completa del proyecto con todas las funcionalidades terminadas desde:
Pueden seguir el curso completo y aprender a desarrollar un Sistema de Ventas en Csharp.Net utilizando como IDE de desarrollo Visual Studio 2013 y como gestor de Base de datos SQL Server 2014 desde:
No se olviden siempre de Visitar mi canal www.youtube.com/jcarlosad7 para ver los nuevos cursos.
Formulario FrmVenta - Mantenimiento
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using CapaNegocio;
namespace CapaPresentacion
{
public partial class FrmVenta : Form
{
private bool IsNuevo = false;
public int Idtrabajador;
private DataTable dtDetalle;
private decimal totalPagado = 0;
private static FrmVenta _instancia;
//Creamos una instancia para poder utilizar los
//Objetos del formulario
public static FrmVenta GetInstancia()
{
if (_instancia == null)
{
_instancia = new FrmVenta();
}
return _instancia;
}
//Creamos un método para enviar los valores recibidos
//del cliente
public void setCliente(string idcliente, string nombre)
{
this.txtIdcliente.Text = idcliente;
this.txtCliente.Text = nombre;
}
//Creamos un método para enviar los valores recibidos
//del artículo
public void setArticulo(string iddetalle_articulo, string nombre,Decimal precio_compra,Decimal precio_venta,int stock,DateTime fecha_vencimiento)
{
this.txtIddetalle_ingreso.Text = iddetalle_articulo;
this.txtArticulo.Text = nombre;
this.txtPrecio_Compra.Text = Convert.ToString(precio_compra);
this.txtPrecio_Venta.Text = Convert.ToString(precio_venta);
this.txtStock.Text = Convert.ToString(stock);
this.dtFecha_Vencimiento.Value = fecha_vencimiento;
}
public FrmVenta()
{
InitializeComponent();
this.ttMensaje.SetToolTip(this.txtCliente, "Seleccione un Cliente");
this.ttMensaje.SetToolTip(this.txtSerie, "Ingrese la serie del comprobante");
this.ttMensaje.SetToolTip(this.txtCorrelativo, "Ingrese el número del comprobante");
this.ttMensaje.SetToolTip(this.txtCantidad, "Ingrese la cantidad de compra");
this.ttMensaje.SetToolTip(this.txtArticulo, "Seleccione el artículo");
this.txtIdcliente.Visible = false;
this.txtCliente.ReadOnly = true;
this.txtIddetalle_ingreso.Visible = false;
this.txtArticulo.ReadOnly = true;
this.dtFecha_Vencimiento.Enabled = false;
this.txtPrecio_Compra.ReadOnly = true;
this.txtStock.ReadOnly = true;
}
//Mostrar Mensaje de Confirmación
private void MensajeOk(string mensaje)
{
MessageBox.Show(mensaje, "Sistema de Ventas", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
//Mostrar Mensaje de Error
private void MensajeError(string mensaje)
{
MessageBox.Show(mensaje, "Sistema de Ventas", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
//Limpiar todos los controles del formulario
private void Limpiar()
{
this.txtIdventa.Text = string.Empty;
this.txtIdcliente.Text = string.Empty;
this.txtCliente.Text = string.Empty;
this.txtSerie.Text = string.Empty;
this.txtCorrelativo.Text = string.Empty;
this.txtIgv.Text = "18";
this.lblTotalPagado.Text = "0,0";
this.txtDescuento.Text = "0";
this.crearTabla();
}
private void limpiarDetalle()
{
this.txtIddetalle_ingreso.Text = string.Empty;
this.txtArticulo.Text = string.Empty;
this.txtCantidad.Text = string.Empty;
this.txtPrecio_Compra.Text = string.Empty;
this.txtPrecio_Venta.Text = string.Empty;
this.txtStock.Text = String.Empty;
this.txtDescuento.Text = "0";
}
//Habilitar los controles del formulario
private void Habilitar(bool valor)
{
this.txtIdventa.ReadOnly = !valor;
this.txtSerie.ReadOnly = !valor;
this.txtCorrelativo.ReadOnly = !valor;
this.txtIgv.Enabled = valor;
this.dtFecha.Enabled = valor;
this.cbTipo_Comprobante.Enabled = valor;
this.txtCantidad.ReadOnly = !valor;
this.txtPrecio_Compra.ReadOnly = !valor;
this.txtPrecio_Venta.ReadOnly = !valor;
this.dtFecha_Vencimiento.Enabled = valor;
this.btnAgregar.Enabled = valor;
this.btnQuitar.Enabled = valor;
this.btnBuscarProveedor.Enabled = valor;
this.btnBuscarArticulo.Enabled = valor;
}
//Habilitar los botones
private void Botones()
{
if (this.IsNuevo) //Alt + 124
{
this.Habilitar(true);
this.btnNuevo.Enabled = false;
this.btnGuardar.Enabled = true;
this.btnCancelar.Enabled = true;
}
else
{
this.Habilitar(false);
this.btnNuevo.Enabled = true;
this.btnGuardar.Enabled = false;
this.btnCancelar.Enabled = false;
}
}
//Método para ocultar columnas
private void OcultarColumnas()
{
this.dataListado.Columns[0].Visible = false;
this.dataListado.Columns[1].Visible = false;
}
//Método Mostrar
private void Mostrar()
{
this.dataListado.DataSource = NVenta.Mostrar();
this.OcultarColumnas();
lblTotal.Text = "Total de Registros: " + Convert.ToString(dataListado.Rows.Count);
}
//Método BuscarFecha
private void BuscarFechas()
{
this.dataListado.DataSource = NVenta.BuscarFechas(this.dtFecha1.Value.ToString("dd/MM/yyyy"), this.dtFecha2.Value.ToString("dd/MM/yyyy"));
this.OcultarColumnas();
lblTotal.Text = "Total de Registros: " + Convert.ToString(dataListado.Rows.Count);
}
//Método BuscarDetalles
private void MostrarDetalles()
{
this.datalistadoDetalle.DataSource = NVenta.MostrarDetalle(this.txtIdventa.Text);
//this.OcultarColumnas();
//lblTotal.Text = "Total de Registros: " + Convert.ToString(dataListado.Rows.Count);
//this.datalistadoDetalle.AutoGenerateColumns = false;
}
//Crea la tabla de Detalle
private void crearTabla()
{
//Crea la tabla con el nombre de Detalle
this.dtDetalle = new DataTable("Detalle");
//Agrega las columnas que tendra la tabla
this.dtDetalle.Columns.Add("iddetalle_ingreso", System.Type.GetType("System.Int32"));
this.dtDetalle.Columns.Add("articulo", System.Type.GetType("System.String"));
this.dtDetalle.Columns.Add("cantidad", System.Type.GetType("System.Int32"));
this.dtDetalle.Columns.Add("precio_venta", System.Type.GetType("System.Decimal"));
this.dtDetalle.Columns.Add("descuento", System.Type.GetType("System.Decimal"));
this.dtDetalle.Columns.Add("subtotal", System.Type.GetType("System.Decimal"));
//Relacionamos nuestro datagridview con nuestro datatable
this.datalistadoDetalle.DataSource = this.dtDetalle;
}
private void FrmVenta_Load(object sender, EventArgs e)
{
//Para ubicar al formulario en la parte superior del contenedor
this.Top = 0;
this.Left = 0;
//Mostrar
this.Mostrar();
//Deshabilita los controles
this.Habilitar(false);
//Establece los botones
this.Botones();
this.crearTabla();
}
private void btnBuscar_Click(object sender, EventArgs e)
{
this.BuscarFechas();
}
private void btnEliminar_Click(object sender, EventArgs e)
{
try
{
DialogResult Opcion;
Opcion = MessageBox.Show("Realmente Desea Anular la(s) venta(s)", "Sistema de Ventas", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
if (Opcion == DialogResult.OK)
{
string Codigo;
string Rpta = "";
foreach (DataGridViewRow row in dataListado.Rows)
{
if (Convert.ToBoolean(row.Cells[0].Value))
{
Codigo = Convert.ToString(row.Cells[1].Value);
Rpta = NVenta.Eliminar(Convert.ToInt32(Codigo));
if (Rpta.Equals("OK"))
{
this.MensajeOk("Se Anuló Correctamente el registro");
}
else
{
this.MensajeError(Rpta);
}
}
}
this.Mostrar();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + ex.StackTrace);
}
}
private void dataListado_DoubleClick(object sender, EventArgs e)
{
this.txtIdventa.Text = Convert.ToString(this.dataListado.CurrentRow.Cells["idventa"].Value);
this.txtCliente.Text = Convert.ToString(this.dataListado.CurrentRow.Cells["cliente"].Value);
this.dtFecha.Value = Convert.ToDateTime(this.dataListado.CurrentRow.Cells["fecha"].Value);
this.cbTipo_Comprobante.Text = Convert.ToString(this.dataListado.CurrentRow.Cells["tipo_comprobante"].Value);
this.txtSerie.Text = Convert.ToString(this.dataListado.CurrentRow.Cells["serie"].Value);
this.txtCorrelativo.Text = Convert.ToString(this.dataListado.CurrentRow.Cells["correlativo"].Value);
this.lblTotalPagado.Text = Convert.ToString(this.dataListado.CurrentRow.Cells["Total"].Value);
this.MostrarDetalles();
this.tabControl1.SelectedIndex = 1;
}
private void chkEliminar_CheckedChanged(object sender, EventArgs e)
{
if (chkEliminar.Checked)
{
this.dataListado.Columns[0].Visible = true;
}
else
{
this.dataListado.Columns[0].Visible = false;
}
}
private void dataListado_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == dataListado.Columns["Eliminar"].Index)
{
DataGridViewCheckBoxCell ChkEliminar =
(DataGridViewCheckBoxCell)dataListado.Rows[e.RowIndex].Cells["Eliminar"];
ChkEliminar.Value = !Convert.ToBoolean(ChkEliminar.Value);
}
}
private void btnNuevo_Click(object sender, EventArgs e)
{
this.IsNuevo = true;
this.Botones();
this.Limpiar();
this.limpiarDetalle();
this.Habilitar(true);
this.txtSerie.Focus();
}
private void btnCancelar_Click(object sender, EventArgs e)
{
this.IsNuevo = false;
this.Botones();
this.Limpiar();
this.Limpiar();
this.txtIdventa.Text = string.Empty;
}
private void btnGuardar_Click(object sender, EventArgs e)
{
try
{
//La variable que almacena si se inserto
//o se modifico la tabla
string Rpta = "";
if (this.txtIdcliente.Text == string.Empty || this.txtSerie.Text == string.Empty || txtCorrelativo.Text == string.Empty || txtIgv.Text == string.Empty)
{
MensajeError("Falta ingresar algunos datos, serán remarcados");
errorIcono.SetError(txtCliente, "Seleccione un Proveedor");
errorIcono.SetError(txtSerie, "Ingrese la serie del comprobante");
errorIcono.SetError(txtCorrelativo, "Ingrese el número del comprobante");
errorIcono.SetError(txtIgv, "Ingrese el porcentaje de IGV");
}
else
{
if (this.IsNuevo)
{
//Vamos a insertar un Ingreso
Rpta = NVenta.Insertar(Convert.ToInt32(txtIdcliente.Text),
Idtrabajador,
dtFecha.Value, cbTipo_Comprobante.Text,
txtSerie.Text, txtCorrelativo.Text,
Convert.ToDecimal(txtIgv.Text), "EMITIDO", dtDetalle);
}
//Si la respuesta fue OK, fue porque se
//o inserto la venta
//de forma correcta
if (Rpta.Equals("OK"))
{
this.MensajeOk("Se insertó de forma correcta el registro");
}
else
{
//Mostramos el mensaje de error
this.MensajeError(Rpta);
}
this.IsNuevo = false;
this.Botones();
this.Limpiar();
this.limpiarDetalle();
this.Mostrar();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + ex.StackTrace);
}
}
private void btnAgregar_Click(object sender, EventArgs e)
{
try
{
if (this.txtIddetalle_ingreso.Text == string.Empty || this.txtCantidad.Text == string.Empty || txtPrecio_Venta.Text == string.Empty)
{
MensajeError("Falta ingresar algunos datos, serán remarcados");
errorIcono.SetError(txtArticulo, "Seleccione un Artículo");
errorIcono.SetError(txtCantidad, "Ingrese el stock inicial");
errorIcono.SetError(txtPrecio_Venta, "Ingrese el precio de Venta");
}
else
{
//Variable que va a indicar si podemos registrar el detalle
bool registrar = true;
foreach (DataRow row in dtDetalle.Rows)
{
if (Convert.ToInt32(row["iddetalle_ingreso"]) == Convert.ToInt32(this.txtIddetalle_ingreso.Text))
{
registrar = false;
this.MensajeError("Ya se encuentra el artículo en el detalle");
}
}
//Si podemos registrar el producto en el detalle
if (registrar=true && Convert.ToInt32(this.txtCantidad.Text)<=Convert.ToInt32(this.txtStock.Text))
{
//Calculamos el sub total del detalle sin descuento
decimal subTotal = Convert.ToDecimal(this.txtPrecio_Venta.Text) * Convert.ToDecimal(txtCantidad.Text) - Convert.ToDecimal(txtDescuento.Text);
totalPagado = totalPagado + subTotal;
this.lblTotalPagado.Text = totalPagado.ToString("#0.00#");
//Agregamos al fila a nuestro datatable
DataRow row = this.dtDetalle.NewRow();
row["iddetalle_ingreso"] = Convert.ToInt32(this.txtIddetalle_ingreso.Text);
row["articulo"] = this.txtArticulo.Text;
row["cantidad"] = Convert.ToInt32(this.txtCantidad.Text);
row["precio_venta"] = Convert.ToDecimal(this.txtPrecio_Venta.Text);
row["descuento"] = Convert.ToDecimal(this.txtDescuento.Text);
row["subTotal"] = subTotal;
this.dtDetalle.Rows.Add(row);
this.limpiarDetalle();
}
else
{
this.MensajeError("No hay Stock Disponible");
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + ex.StackTrace);
}
}
private void btnQuitar_Click(object sender, EventArgs e)
{
try
{
//Indice dila actualmente seleccionado y que vamos a eliminar
int indiceFila = this.datalistadoDetalle.CurrentCell.RowIndex;
//Fila que vamos a eliminar
DataRow row = this.dtDetalle.Rows[indiceFila];
//Disminuimos el total a pagar
this.totalPagado = this.totalPagado - Convert.ToDecimal(row["subTotal"].ToString());
this.lblTotalPagado.Text = totalPagado.ToString("#0.00#");
//Removemos la fila
this.dtDetalle.Rows.Remove(row);
}
catch (Exception ex)
{
MensajeError("No hay fila para remover");
}
}
private void FrmVenta_FormClosing(object sender, FormClosingEventArgs e)
{
_instancia = null;
}
private void btnBuscarProveedor_Click(object sender, EventArgs e)
{
FrmVistaCliente_Venta vista = new FrmVistaCliente_Venta();
vista.ShowDialog();
}
private void btnBuscarArticulo_Click(object sender, EventArgs e)
{
FrmVistaArticulo_Venta vista = new FrmVistaArticulo_Venta();
vista.ShowDialog();
}
}
}
Video 35: Sistema de Ventas C# - Visual Studio 2013 - Sql Server 2014 (35-40) Formulario Venta 2
Saludos Imperio, un abrazo a la distancia.
Diseño Sistema de Ventas C# - Visual Studio 2013 y Sql Server 2014 (35-41) Gestión Ventas
Reviewed by IncanatoIt-ad
on
21:46
Rating:
No se puede descargar el programa ya hecho?
ResponderEliminarPorque si tengo la lista de errores limpia, no inicia el programa, me tira una pantalla de error
ResponderEliminarDónde puedo encontrar el código fuente completo de este proyecto? En este capítulo solamente se encuentra hasta el vídeo 30... Te agradezco.
ResponderEliminarAqui tambien me da el error al buscar por fechas y me marca el metodo ocultar columnas, como puede resolverse?
ResponderEliminarSaludos
me sale el siguiente el error en ocultar columnas y no sale el formulario de venta me pueden ayudar porfavor
ResponderEliminar