Хорошего времени!

- под решением я добавляю новый элемент и выбираю веб-форму с главной страницей — так создается мастер.
[*]
- под решением я нажимаю «Добавить новый элемент». Выбрана веб-форма с главной страницей
INICIO
Factura
N. Factura
Base Imponible IVA 0%:
Base Imponible IVA 12%:
IVA:
Total a Pagar:
Detalle
Nombre
Cantidad
Precio Unitario
Total
IVA
Я не думаю, что это правильно, это для web.config
пытаемся понять index.asp
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using iTextSharp.text;
using iTextSharp.text.pdf;
namespace Factura
{
public partial class Index : System.Web.UI.Page
{
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["conexion"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ddlIVA.DataSource = ObtenerTiposIVADesdeBaseDeDatos();
ddlIVA.DataTextField = "Descripcion";
ddlIVA.DataValueField = "ID";
ddlIVA.DataBind();
int ultimoNumeroFactura = ObtenerUltimoNumeroFactura();
txtFactura.Text = ultimoNumeroFactura.ToString();
}
}
private int ObtenerUltimoNumeroFactura()
{
int ultimoNumeroFactura = 0;
// Conectar con la base de datos y obtener el último número de factura
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand("SELECT MAX(FacturaID) FROM Facturas", connection);
connection.Open();
object result = command.ExecuteScalar();
if (result != DBNull.Value)
{
ultimoNumeroFactura = Convert.ToInt32(result);
}
}
return ultimoNumeroFactura + 1; // Incrementar el último número de factura para obtener el siguiente número
}
private DataTable ObtenerTiposIVADesdeBaseDeDatos()
{
DataTable tiposIVA = new DataTable();
// Crea una conexión a la base de datos utilizando la cadena de conexión definida en el web.config
using (SqlConnection connection = new SqlConnection(connectionString))
{
// Crea un comando para llamar al procedimiento almacenado
using (SqlCommand command = new SqlCommand("ObtenerTiposIVA", connection))
{
// Especifica que el comando es un procedimiento almacenado
command.CommandType = CommandType.StoredProcedure;
// Abre la conexión
connection.Open();
// Ejecuta el comando y llena el DataTable con los resultados
using (SqlDataAdapter adapter = new SqlDataAdapter(command))
{
adapter.Fill(tiposIVA);
}
}
}
return tiposIVA;
}
protected void btnAgregarProducto_Click(object sender, EventArgs e)
{
// Deshabilitar los controles existentes
txtNombreProducto.Enabled = false;
txtCantidad.Enabled = false;
txtPrecioUnitario.Enabled = false;
txtTotal.Enabled = false;
ddlIVA.Enabled = false;
}
protected void txtPrecioUnitario_TextChanged(object sender, EventArgs e)
{
// Verificar si el valor ingresado es un número válido
decimal precioUnitario;
if (decimal.TryParse(txtPrecioUnitario.Text, out precioUnitario))
{
// Obtener la cantidad ingresada
int cantidad;
if (int.TryParse(txtCantidad.Text, out cantidad))
{
// Calcular el total multiplicando el precio unitario por la cantidad
decimal total = precioUnitario * cantidad;
// Mostrar el total en el TextBox de txtTotal
txtTotal.Text = total.ToString();
}
else
{
// Si la cantidad no es un número válido, mostrar un mensaje de error
txtTotal.Text = "Error: Cantidad no válida";
}
}
else
{
// Si el precio unitario no es un número válido, mostrar un mensaje de error
txtTotal.Text = "Error: Precio unitario no válido";
}
}
protected void txtCantidad_TextChanged(object sender, EventArgs e)
{
// Verificar si el valor ingresado es un número válido
int cantidad;
if (int.TryParse(txtCantidad.Text, out cantidad))
{
// Obtener el precio unitario
decimal precioUnitario;
if (decimal.TryParse(txtPrecioUnitario.Text, out precioUnitario))
{
// Calcular el total multiplicando el precio unitario por la cantidad
decimal total = precioUnitario * cantidad;
// Mostrar el total en el TextBox de txtTotal
txtTotal.Text = total.ToString();
}
else
{
// Si el precio unitario no es un número válido, mostrar un mensaje de error
txtTotal.Text = "Error: Precio unitario no válido";
}
}
else
{
// Si la cantidad no es un número válido, mostrar un mensaje de error
txtTotal.Text = "Error: Cantidad no válida";
}
}
protected void ddlIVA_SelectedIndexChanged(object sender, EventArgs e)
{
// Obtener el valor seleccionado del DropDownList de IVA
string iva = ddlIVA.SelectedItem.Text;
// Obtener el total desde el TextBox de total
decimal total;
if (decimal.TryParse(txtTotal.Text, out total))
{
if (iva == "IVA 0%")
{
txtBaseImponible0.Text = txtTotal.Text;
CalcularTotalPagar();
}
else if (iva == "IVA 12%")
{
txtBaseImponible12.Text = txtTotal.Text;
decimal baseImponible12;
if (decimal.TryParse(txtBaseImponible12.Text, out baseImponible12))
{
// Calcular el 12% del valor
decimal iva12 = baseImponible12 * 0.12m;
// Asignar el valor calculado a txtIVA
txtIVA.Text = iva12.ToString();
}
CalcularTotalPagar();
}
}
}
private void CalcularTotalPagar()
{
// Obtener los valores de los TextBox y establecerlos en 0 si están vacíos
decimal baseImponible0 = string.IsNullOrEmpty(txtBaseImponible0.Text) ? 0 : decimal.Parse(txtBaseImponible0.Text);
decimal baseImponible12 = string.IsNullOrEmpty(txtBaseImponible12.Text) ? 0 : decimal.Parse(txtBaseImponible12.Text);
decimal iva = string.IsNullOrEmpty(txtIVA.Text) ? 0 : decimal.Parse(txtIVA.Text);
// Calcular el total a pagar sumando las bases imponibles y el IVA
decimal totalPagar = baseImponible0 + baseImponible12 + iva;
// Mostrar el resultado en el TextBox txtTotalPagar
txtTotalPagar.Text = totalPagar.ToString();
}
protected void btnGuardarFactura_Click(object sender, EventArgs e)
{
// Obtener los datos de la factura
decimal baseImponible0 = decimal.TryParse(txtBaseImponible0.Text, out decimal imp0) ? imp0 : 0;
decimal baseImponible12 = decimal.TryParse(txtBaseImponible12.Text, out decimal imp12) ? imp12 : 0;
decimal iva = decimal.TryParse(txtIVA.Text, out decimal ivaValue) ? ivaValue : 0;
decimal totalPagar = decimal.TryParse(txtTotalPagar.Text, out decimal total) ? total : 0;
// Llamar al procedimiento almacenado para insertar la factura en la base de datos
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand("InsertarFactura", connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("@BaseImponible0", baseImponible0);
command.Parameters.AddWithValue("@BaseImponible12", baseImponible12);
command.Parameters.AddWithValue("@IVA", iva);
command.Parameters.AddWithValue("@TotalPagar", totalPagar);
connection.Open();
// Ejecutar el comando y obtener el ID de la factura generada
int facturaID = Convert.ToInt32(command.ExecuteScalar());
// Generar el PDF con el ID de la factura
GenerarPDF(facturaID);
}
}
private void LimpiarCampos()
{
int ultimoNumeroFactura = ObtenerUltimoNumeroFactura();
txtFactura.Text = ultimoNumeroFactura.ToString();
txtBaseImponible0.Text = string.Empty;
txtBaseImponible12.Text = string.Empty;
txtIVA.Text = string.Empty;
txtTotalPagar.Text = string.Empty;
txtNombreProducto.Text = string.Empty;
txtCantidad.Text = string.Empty;
txtPrecioUnitario.Text = string.Empty;
txtTotal.Text = string.Empty;
}
private void GenerarPDF(int facturaID)
{
// Crear un nuevo documento PDF
Document doc = new Document(PageSize.A4);
// Crear un flujo de memoria para escribir el PDF
MemoryStream memoryStream = new MemoryStream();
PdfWriter writer = PdfWriter.GetInstance(doc, memoryStream);
// Abrir el documento
doc.Open();
// Crear el contenido del PDF utilizando los datos de la factura
PdfPTable table = new PdfPTable(5);
table.AddCell("FacturaID");
table.AddCell("BaseImponibleIVA0");
table.AddCell("BaseImponibleIVA12");
table.AddCell("IVA");
table.AddCell("TotalPagar");
// Obtener los datos de la factura de la base de datos
DataTable dtFactura = ObtenerDatosFactura(facturaID);
// Agregar los datos de la factura a la tabla del PDF
foreach (DataRow row in dtFactura.Rows)
{
table.AddCell(row["FacturaID"].ToString());
table.AddCell(row["BaseImponibleIVA0"].ToString());
table.AddCell(row["BaseImponibleIVA12"].ToString());
table.AddCell(row["IVA"].ToString());
table.AddCell(row["TotalPagar"].ToString());
}
// Agregar la tabla al documento
doc.Add(table);
// Cerrar el documento
doc.Close();
// Escribir el PDF en el flujo de memoria
writer.CloseStream = false;
writer.Close();
// Enviar el PDF como respuesta al navegador
byte[] pdfBytes = memoryStream.ToArray();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=Factura.pdf");
Response.Buffer = true;
Response.Clear();
Response.OutputStream.Write(pdfBytes, 0, pdfBytes.Length);
Response.OutputStream.Flush();
lblMensaje.Text = "Factura guardada exitosamente.";
lblMensaje.Visible = true;
// Limpiar los campos de texto
LimpiarCampos();
Response.End();
// Mostrar mensaje de éxito
}
private DataTable ObtenerDatosFactura(int facturaID)
{
DataTable dtFactura = new DataTable();
// Conectar con la base de datos y obtener los datos de la factura
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand("SELECT * FROM Facturas WHERE BaseImponibleIVA0 = @BaseImponible0", connection);
command.Parameters.AddWithValue("@BaseImponible0", facturaID);
SqlDataAdapter adapter = new SqlDataAdapter(command);
adapter.Fill(dtFactura);
}
return dtFactura;
}
protected void btnLimpiar_Click(object sender, EventArgs e)
{
int ultimoNumeroFactura = ObtenerUltimoNumeroFactura();
txtFactura.Text = ultimoNumeroFactura.ToString();
txtBaseImponible0.Text = string.Empty;
txtBaseImponible12.Text = string.Empty;
txtIVA.Text = string.Empty;
txtTotalPagar.Text = string.Empty;
txtNombreProducto.Text = string.Empty;
txtCantidad.Text = string.Empty;
txtPrecioUnitario.Text = string.Empty;
txtTotal.Text = string.Empty;
}
}
}
Подробнее здесь: https://stackoverflow.com/questions/782 ... -new-at-th