private void Accion(int Naccion, string xmes, string xnumero)
        {
            switch (Naccion)
            {
                case 1:
                    UltimoNumeroRegistro();
                    procesanumero();
                    break;
                case 2:
                    CargaDatos();
                    u_n_opsel = 2;
                    refrescacontroles();
                    break;
                case 3:
                    //eliminar
                    DataTable tmptabla = new DataTable();
                    tb_co_VentascabBL BL = new tb_co_VentascabBL();
                    tb_co_Ventascab BE = new tb_co_Ventascab();

                    BE.perianio = VariablesPublicas.perianio;
                    BE.perimes = VariablesPublicas.PADL(txtMes.Text.Trim(), 2, "0");
                    BE.moduloid = modulo.ToString();
                    BE.local = local.ToString();
                    BE.diarioid = cboSubdiario.SelectedValue.ToString();
                    BE.asiento = VariablesPublicas.PADL(txtAsiento.Text.Trim(), 6, "0");

                    tmptabla = BL.GetAll(VariablesPublicas.EmpresaID.ToString(), BE).Tables[0];
                    if (tmptabla.Rows.Count > 0)
                    {
                        string message = "Desea eliminar Registro de Ventas " + tmptabla.Rows[0]["perianio"] + "/" + tmptabla.Rows[0]["diarioid"] + "/" + tmptabla.Rows[0]["perimes"] + "-" + tmptabla.Rows[0]["asiento"] + " ...?";
                        string caption = "Mensaje del Sistema";
                        MessageBoxButtons buttons = MessageBoxButtons.YesNo;
                        DialogResult result;
                        // Muestra el cuadro de mensaje.
                        result = DevExpress.XtraEditors.XtraMessageBox.Show(this, message, caption, buttons, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
                        if (result == DialogResult.Yes)
                        {
                            tb_co_VentasBL BL1 = new tb_co_VentasBL();
                            tb_co_Ventas BE1 = new tb_co_Ventas();

                            BE1.perianio = VariablesPublicas.perianio;
                            BE1.perimes = txtMes.Text;
                            BE1.moduloid = modulo.ToString();
                            BE1.local = local.ToString();
                            BE1.diarioid = cboSubdiario.SelectedValue.ToString();
                            BE1.asiento = VariablesPublicas.PADL(txtAsiento.Text.Trim(), 6, "0");
                            //if (BL1.Delete(VariablesPublicas.EmpresaID.ToString(), BE1))
                            //{
                            //    txtAsiento.Focus();
                            //}
                            //else
                            //{
                            //    Frm_Class.ShowError(BL1.Sql_Error, this);
                            //}
                        }
                    }
                    CargaDatos();
                    break;
                case 5:
                    CargaDatos();
                    refrescacontroles();
                    break;
                //case 6:
                //    //Impresion
                //    ReportesContabilidad.Frm_ReporteVouchers frm = new ReportesContabilidad.Frm_ReporteVouchers();
                //    //frm._tipComprobante = VariablesPublicas.CodVoucherVentas;
                //    frm._tipComprobante = cboSubdiario.SelectedValue.ToString();
                //    frm._nroComprobante = (xmes.Trim().Length == 0 ? txtMes.Text : xmes) + (xnumero.Trim().Length == 0 ? txtAsiento.Text : xnumero);
                //    frm._xModulo = modulo.ToString();
                //    frm._xLocal = local.ToString();
                //    frm._tipoOperacion = "1";
                //    frm.Owner = this;
                //    frm.ShowInTaskbar = false;
                //    frm.ShowDialog();
                //    break;
            }
        }
        private bool Validacion()
        {
            object xobjeto = null;
            int lc_cont = 0;
            string xmsgstring = "";
            DataTable tmptabla = new DataTable();
            dynamic xfill = "...";
            if (txtNumero.Text.Trim().Length == 0)
            {
                xmsgstring = xmsgstring + "\r\n" + "Ingrese Número de Comprobante...?";
                xobjeto = txtNumero;
            }
            //if (txtNumFin.Text.Trim().Length == 0)
            //{
            //    xmsgstring = xmsgstring + "\r\n" + "Ingrese Número de Comprobante Final...?";
            //    xobjeto = txtNumFin;
            //}
            if (txtRuc.Text.Trim().Length == 0)
            {
                xmsgstring = xmsgstring + "\r\n" + "Ingrese Cliente...?";
                xobjeto = txtRuc;
            }
            else
            {
                try
                {
                    clienteBL BL = new clienteBL();
                    tb_cliente BE = new tb_cliente();

                    BE.nmruc = txtRuc.Text;
                    if ((BL.GetAll(VariablesPublicas.EmpresaID.ToString(), BE).Tables[0]).Rows.Count == 0)
                    {
                        xmsgstring = (xmsgstring + ("\r\n" + "Cliente no existe...?"));
                        xobjeto = txtRuc;
                    }
                }
                catch (Exception ex)
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            if (txtTipoventa.Text.Trim().Length == 0)
            {
                xmsgstring = xmsgstring + "\r\n" + "Ingrese Tipo Venta...?";
                xobjeto = txtTipoventa;
            }
            else
            {
            }
            Decimal vmntipocambio = VariablesPublicas.StringtoDecimal(txtTipocambio.Text);
            if (vmntipocambio == 0)
            {
                xmsgstring = xmsgstring + "\r\n" + "Ingrese Tipo de Cambio...?";
                xobjeto = fRegistro;
            }
            if (validaduplicidad())
            {
                xmsgstring = xmsgstring + xfill;
            }
            if ((txtGlosa.Text.Trim()).Trim().Length == 0)
            {
                xmsgstring = xmsgstring + "\r\n" + "Ingrese glosa...?";
                xobjeto = txtGlosa;
            }
            string xcodtmp = "";
            string xcodtmpr = "";
            double canttmp = 0;
            DataTable otabla = new DataTable();
            if (DetFacturacion.Rows.Count == 0)
            {
                xmsgstring = xmsgstring + "\r\n" + "Ingrese detalles al movimiento...?";
                xobjeto = GridExaminar;
            }
            if (xmsgstring.Trim().Length == 0)
            {
                for (lc_cont = 0; lc_cont <= DetFacturacion.Rows.Count - 1; lc_cont++)
                {
                    // Validando Rubro
                    xcodtmp = "";
                    if (!object.ReferenceEquals(DetFacturacion.Rows[lc_cont]["rubroid"], DBNull.Value))
                    {
                        xcodtmpr = DetFacturacion.Rows[lc_cont]["rubroid"].ToString();
                    }
                    if (xcodtmpr.Trim().Length == 0)
                    {
                        xcodtmpr = "...";
                    }
                    if (xcodtmpr.Trim().Length > 0)
                    {
                        try
                        {
                            tb_co_rubroventasBL BL = new tb_co_rubroventasBL();
                            tb_co_rubroventas BE = new tb_co_rubroventas();

                            BE.rubroid = xcodtmpr;
                            tmptabla = BL.GetAll(VariablesPublicas.EmpresaID.ToString(), BE).Tables[0];

                            if (tmptabla.Rows.Count == 0)
                            {
                                xmsgstring = (xmsgstring + ("\r\n" + "Rubro de Ventas no Existe...?"));
                                xobjeto = GridExaminar;
                            }
                            if (tmptabla.Rows.Count > 0)
                            {
                                if (tmptabla.Rows[0]["cuentaid"].ToString().Trim().Length != 7)
                                {
                                    xmsgstring = (xmsgstring + ("\r\n" + "Rubro no Asociado a una Cuenta Contable Válida...?"));
                                    xobjeto = GridExaminar;
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    // Validando Item
                    if (!object.ReferenceEquals(DetFacturacion.Rows[lc_cont]["productid"], DBNull.Value))
                    {
                        xcodtmp = DetFacturacion.Rows[lc_cont]["productid"].ToString();
                    }
                    else
                    {
                        xcodtmp = "";
                    }
                    if (xcodtmp.Trim().Length > 0)
                    {
                        try
                        {
                            tb_pt_productoBL BL = new tb_pt_productoBL();
                            tb_pt_producto BE = new tb_pt_producto();
                            BE.productid = xcodtmp;
                            otabla = BL.GetAll(VariablesPublicas.EmpresaID.ToString(), BE).Tables[0];
                            if (otabla.Rows.Count == 0)
                            {
                                xmsgstring = "Código de Artículo no existe...?";
                                xobjeto = GridExaminar;
                            }
                        }
                        catch (Exception ex)
                        {
                            DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    // Validando Precios
                    if (!object.ReferenceEquals(DetFacturacion.Rows[lc_cont]["precunit"], DBNull.Value))
                    {
                        canttmp = Convert.ToDouble(DetFacturacion.Rows[lc_cont]["precunit"]);
                    }
                    else
                    {
                        canttmp = 0;
                    }
                    if (canttmp <= 0)
                    {
                        xmsgstring = xmsgstring + "\r\n" + "Ingrese precio...?";
                        xobjeto = GridExaminar;
                    }
                    if (!object.ReferenceEquals(DetFacturacion.Rows[lc_cont]["cantidad"], DBNull.Value))
                    {
                        canttmp = Convert.ToDouble(DetFacturacion.Rows[lc_cont]["cantidad"]);
                    }
                    else
                    {
                        canttmp = 0;
                    }
                    if (canttmp <= 0)
                    {
                        xmsgstring = xmsgstring + "\r\n" + "Ingrese Cantidades...?";
                        xobjeto = GridExaminar;
                    }
                    // Validando Centro de Costo
                    DataTable tmptablarelacionccosto = new DataTable();
                    string vmccosto;
                    vmccosto = "...";
                    if (!(DetFacturacion.Rows[lc_cont]["cencosid"] == DBNull.Value))
                    {
                        if (DetFacturacion.Rows[lc_cont]["cencosid"].ToString().Trim().Length > 0)
                        {
                            vmccosto = DetFacturacion.Rows[lc_cont]["cencosid"].ToString();
                        }
                    }
                    try
                    {
                        centrocostoBL BL = new centrocostoBL();
                        tb_centrocosto BE = new tb_centrocosto();

                        if (xcodtmpr != "...")
                        {
                            BE.cencosdivi = Equivalencias.Mid(tmptabla.Rows[0]["cuentaid"].ToString(), 1, 1);
                            tmptablarelacionccosto = BL.GetAll(VariablesPublicas.EmpresaID.ToString(), BE).Tables[0];
                        }
                        if (tmptablarelacionccosto.Rows.Count > 0)
                        {
                            int qqqcont;
                            bool zhalladoccosto = false;
                            for (qqqcont = 0; (qqqcont <= (tmptablarelacionccosto.Rows.Count - 1)); qqqcont++)
                            {
                                if (tmptablarelacionccosto.Rows[qqqcont]["cencosid"].ToString() == vmccosto)
                                {
                                    zhalladoccosto = true;
                                    break;
                                }
                            }
                            if (!zhalladoccosto)
                            {
                                xmsgstring = (xmsgstring + ("\r\n" + "Centro de Costo no asociado al Rubro...?"));
                            }
                            else
                            {
                                for (qqqcont = 0; (qqqcont <= (GridExaminar.Rows.Count - 1)); qqqcont++)
                                {
                                    if (GridExaminar.Rows[qqqcont].Cells["asientoitems"].Value == DetFacturacion.Rows[lc_cont]["asientoitems"])
                                    {
                                        if (GridExaminar.CurrentCell == null)
                                        {
                                            GridExaminar.CurrentCell = GridExaminar.Rows[qqqcont].Cells["rubroid"];
                                        }
                                        GridExaminar.CurrentCell.ReadOnly = true;
                                        GridExaminar.CurrentCell = GridExaminar.Rows[qqqcont].Cells["cencosid"];
                                        GridExaminar.BeginEdit(true);
                                        GridExaminar.CurrentCell.ReadOnly = false;
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }

                    if ((xmsgstring.Trim().Length > 0))
                    {
                        break;
                    }
                }
            }
            if (xmsgstring.Trim().Length == 0)
            {
                if (u_n_opsel == 1 | (W_KEY0001 != txtRuc.Text + cboTipdoc.SelectedValue + txtSerie.Text + txtNumero.Text))
                {
                    tmptabla = null;
                    try
                    {
                        tb_co_VentascabBL BL = new tb_co_VentascabBL();
                        tb_co_Ventascab BE = new tb_co_Ventascab();

                        BE.nmruc = txtRuc.Text;
                        BE.tipdoc = cboTipdoc.SelectedValue.ToString();
                        BE.serdoc = txtSerie.Text;
                        BE.numdoc = txtNumero.Text;

                        tmptabla = BL.GetAll(VariablesPublicas.EmpresaID.ToString(), BE).Tables[0];

                        if (!(tmptabla == null))
                        {
                            if (tmptabla.Rows.Count > 0)
                            {
                                xmsgstring = ("Documento Ya registrado en Periodo : " + tmptabla.Rows[0]["perianio"] + " Registro Nº " +
                                             tmptabla.Rows[0]["diarioid"] + "/" +
                                             tmptabla.Rows[0]["perimes"] + "-" + tmptabla.Rows[0]["asiento"]);
                                xobjeto = txtNumero;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            if (xobjeto != null)
            {
                try
                {
                    xobjeto = Focus();
                }
                catch (Exception ex)
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            if (xmsgstring.Trim().Length > 0 & xmsgstring.Trim() != xfill)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show(xmsgstring, "Validación de Datos", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            if (xmsgstring.Trim().Length == 0)
            {
                if (!PuedeEditarEliminar("Grabar Nuevo Registro", VariablesPublicas.PADL(fRegistro.Value.Month.ToString(), 2, "0")))
                {
                    xmsgstring = "...";
                }
            }
            if (xmsgstring.Trim().Length == 0)
            {
                return VariablesPublicas.U_ValidaFechaRegistroProvision(VariablesPublicas.perianio, txtMes.Text, fRegistro.Value);
            }
            else
            {
                return xmsgstring.Trim().Length == 0;
            }
        }
        public void u_Roleo(string xtipo)
        {
            string vmnum = "";
            tb_co_VentascabBL BL = new tb_co_VentascabBL();
            tb_co_Ventascab BE = new tb_co_Ventascab();

            BE.perianio = VariablesPublicas.perianio;
            BE.perimes = txtMes.Text;
            BE.moduloid = modulo.ToString();
            BE.local = local.ToString();
            BE.diarioid = cboSubdiario.Text.Substring(0, 4);
            BE.asiento = txtAsiento.Text;
            BE.tipo = xtipo;
            try
            {
                vmnum = BL.GetAsientoRoleo(VariablesPublicas.EmpresaID.ToString(), BE).Tables[0].Rows[0]["numero"].ToString();
            }
            catch (Exception ex)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            if (vmnum.Trim().Length > 0)
            {
                txtMes.Focus();
                txtAsiento.Text = vmnum;
                procesanumero();
            }
        }
        private void UltimoNumeroRegistro()
        {
            tb_co_VentascabBL BL = new tb_co_VentascabBL();
            tb_co_Ventascab BE = new tb_co_Ventascab();

            BE.perianio = VariablesPublicas.perianio;
            BE.perimes = txtMes.Text;
            BE.moduloid = modulo.ToString();//modulo.ToString();
            BE.local = local.ToString();//local.ToString();
            BE.diarioid = cboSubdiario.Text.Substring(0, 4);

            try
            {
                txtAsiento.Text = BL.GetAsientoNume(VariablesPublicas.EmpresaID.ToString(), BE).Tables[0].Rows[0]["asiento"].ToString();
            }
            catch (Exception ex)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        void RecibeTablaaCopiar(string mes, string diario, string numero)
        {
            if ((mes.Trim().Length > 0))
            {
                try
                {
                    tb_co_VentascabBL BL = new tb_co_VentascabBL();
                    tb_co_Ventascab BE = new tb_co_Ventascab();

                    BE.perianio = VariablesPublicas.perianio;
                    BE.perimes = mes;
                    BE.moduloid = modulo.ToString();
                    BE.local = local.ToString();
                    BE.diarioid = diario;
                    BE.asiento = numero;

                    tmptablacab = BL.GetAll(VariablesPublicas.EmpresaID.ToString(), BE).Tables[0];
                    // tmptablacab = ocapa.KAG0300_consulta(GlobalVars.GetInstance.Company, GlobalVars.GetInstance.Periodo, mes, numero, "", "", "", "", "", "");
                }
                catch (Exception ex)
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                try
                {
                    tb_co_VentasdetBL BL = new tb_co_VentasdetBL();
                    tb_co_Ventasdet BE = new tb_co_Ventasdet();

                    BE.perianio = VariablesPublicas.perianio;
                    BE.perimes = mes;
                    BE.moduloid = modulo.ToString();
                    BE.local = local.ToString();
                    BE.diarioid = diario;
                    BE.asiento = numero;

                    tmptabladet = BL.GetAll(VariablesPublicas.EmpresaID.ToString(), BE).Tables[0];
                    // tmptabladet = ocapa.KAP0300_consulta(GlobalVars.GetInstance.Company, GlobalVars.GetInstance.Periodo, mes, numero, "", "");
                }
                catch (Exception ex)
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                CargaDatos();
                tmptablacab = null;
                tmptabladet = null;
            }
        }
        private void Grabar(bool nopideimpresion)
        {
            // Forzar a grabar si pulsa el boton sin finalizar edicion del grid
            if (GridExaminar.IsCurrentCellInEditMode)
            {
                GridExaminar.CommitEdit(DataGridViewDataErrorContexts.Commit);
            }

            #region ** numeracion
            while (u_n_opsel == 1)
            {
                tb_co_VentascabBL BL = new tb_co_VentascabBL();
                tb_co_Ventascab BE = new tb_co_Ventascab();

                BE.perianio = VariablesPublicas.perianio;
                BE.perimes = txtMes.Text;
                BE.moduloid = modulo.ToString();//modulo.ToString();
                BE.local = local.ToString();   //local.ToString();
                BE.diarioid = cboSubdiario.Text.Substring(0, 4);
                BE.asiento = txtAsiento.Text;
                try
                {
                    tmptablacab = BL.GetAll(VariablesPublicas.EmpresaID.ToString(), BE).Tables[0];
                }
                catch (Exception ex)
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                if (tmptablacab.Rows.Count == 0)
                {
                    break;
                }
                UltimoNumeroRegistro();
            }
            #endregion

            #region ** Recapturar Tipo de Cambio
            tributoIgv();
            actualizatipocambio();
            totalizarItem();
            //totalizar();
            #endregion

            if (Validacion())
            {
                // Variables de Cabecera
                tb_co_VentasBL BL = new tb_co_VentasBL();
                tb_co_Ventas BE = new tb_co_Ventas();

                // Variables para Detalle
                tb_co_Ventas.Item Detalle = new tb_co_Ventas.Item();
                List<tb_co_Ventas.Item> ListaItems = new List<tb_co_Ventas.Item>();

                string activo = "0"; //Activo
                string anulad = "9"; //Anulado
                string xMoneda = Equivalencias.Left(cboMoneda.SelectedValue.ToString(), 1);
                xnum = VariablesPublicas.PADL(txtAsiento.Text.Trim(), 6, "0");

                #region **ingreso venta cabecera***
                //caso venta
                BE.perianio = VariablesPublicas.perianio;
                BE.perimes = VariablesPublicas.PADL(txtMes.Text.Trim(), 2, "0");
                BE.moduloid = modulo.ToString();
                BE.local = local.ToString();
                BE.diarioid = VariablesPublicas.PADL(cboSubdiario.SelectedValue.ToString(), 4, "0");
                BE.asiento = VariablesPublicas.PADL(txtAsiento.Text.Trim(), 6, "0");
                BE.origen = cboOrigen.Text.Substring(0, 2);
                if (chkActivo.Checked == true)
                {
                    BE.status = activo;
                }
                if (chkActivo.Checked == false)
                {
                    BE.status = anulad;
                }
                BE.tipdoc = cboTipdoc.Text.Substring(0, 2);
                BE.serdoc = txtSerie.Text;
                BE.numdoc = txtNumero.Text;
                BE.tiperson = xtipopersona;
                BE.tipdid = xtipodocidentidad;
                BE.ctacte = xctacte;
                BE.nmruc = txtRuc.Text.Trim();
                BE.ctactename = txtCtactename.Text.Trim().ToUpper();
                BE.direc = xdirec;
                BE.ubige = xubige;
                BE.fechdoc = Convert.ToDateTime(fRegistro.Text.Trim());
                if (fecVenc.ShowCheckBox)
                {
                    BE.fechvcto = fecVenc.Value;
                }

                BE.condicionvta = "";
                BE.tipcamb = Convert.ToDecimal(txtTipocambio.Text.Trim());
                BE.moneda = cboMoneda.Text.Substring(0, 1);
                BE.ordencompra = txtNumeroorden.Text;
                //Detracciones
                if ((cboServicio.SelectedValue != null))
                {
                    BE.detraccionid = cboServicio.SelectedValue.ToString();
                }
                else
                {
                    BE.detraccionid = DBNull.Value.ToString();
                }
                BE.porcdetraccion = VariablesPublicas.StringtoDecimal(txtPorcdet.Text);
                BE.nctadetraccion = txtCtadetrac.Text;
                BE.glosa = txtGlosa.Text;
                BE.tipoventa = txtTipoventa.Text;
                BE.afectoigvid = cboDestinoigv.Text.Substring(0, 1);

                //datos documento de referencia
                if (cboTipdocref.Enabled)
                {
                    if (cboTipdocref.Text.Length > 0)
                    {
                        BE.tipref = cboTipdocref.Text.Substring(0, 2);
                    }
                    //BE.tipref =  cboTipdocref.Text.Substring(0, 2);
                    BE.serref = txtSerieref.Text.Trim().ToString();
                    BE.numref = txtNumeroref.Text.Trim().ToString();
                    if (fechaRefer.ShowCheckBox)
                    {
                        BE.fechref = fechaRefer.Value;
                    }
                }

                //Aduanas
                if (cboAduana.Enabled)
                {
                    if (!(cboAduana.SelectedValue == null))
                    {
                        BE.aduanaid = cboAduana.SelectedValue.ToString();
                    }
                    BE.aniodua = aduPeriodo.Text;
                    BE.numdua = aduCorrelativo.Text;
                    BE.valorfobdua = VariablesPublicas.StringtoDecimal(aduValorfob.Text);
                    if ((adufEmbarque.ShowCheckBox == true))
                    {
                        BE.fechembdua = adufEmbarque.Value;
                    }
                    if ((adufRegularizacion.ShowCheckBox == true))
                    {
                        BE.fechreguldua = adufRegularizacion.Value;
                    }
                    if (!(cboTipoexportacion.SelectedValue == null))
                    {
                        BE.tipoexportid = cboTipoexportacion.SelectedValue.ToString();
                    }
                }
                BE.afectoigv = chkAfecto.Checked;
                BE.incprec = chkIncluye.Checked;
                BE.afectretencion = chkRetencion.Checked;
                BE.terminovta = _terminoventa;
                BE.dpais = _pais;
                BE.embarcador = _embarque;
                BE.condicionpago = _condpago;
                BE.cartacredito = _cartacredito;
                BE.viaembarque = _codigovia;
                BE.referencia = _referencia;

                BE.bultos = "";
                BE.pesoneto = 0;
                BE.pesobruto = 0;

                switch (xMoneda)
                {
                    case "1":
                        BE.bruto1 = VariablesPublicas.StringtoDecimal(txtValor.Text);
                        BE.dscto1 = VariablesPublicas.StringtoDecimal(txtDctos.Text);
                        BE.valorventa1 = VariablesPublicas.StringtoDecimal(txtVenta.Text);
                        BE.igv1 = VariablesPublicas.StringtoDecimal(txtIgv.Text);
                        BE.total1 = VariablesPublicas.StringtoDecimal(txtTotal.Text);
                        if (BE.tipcamb > 0)
                        {
                            BE.bruto2 = Math.Round(VariablesPublicas.StringtoDecimal(txtValor.Text) / BE.tipcamb, 2);
                            BE.dscto2 = Math.Round(VariablesPublicas.StringtoDecimal(txtDctos.Text) / BE.tipcamb, 2);
                            BE.valorventa2 = Math.Round(VariablesPublicas.StringtoDecimal(txtVenta.Text) / BE.tipcamb, 2);
                            BE.igv2 = Math.Round(VariablesPublicas.StringtoDecimal(txtIgv.Text) / BE.tipcamb, 2);
                            BE.total2 = Math.Round(VariablesPublicas.StringtoDecimal(txtTotal.Text) / BE.tipcamb, 2);

                            BE.valorventa2 = Math.Round(BE.valorventa2, 2);
                            BE.igv2 = Math.Round(BE.igv2, 2);
                            BE.total2 = Math.Round(BE.total2, 2);
                        }

                        break;
                    case "2":
                        BE.bruto2 = VariablesPublicas.StringtoDecimal(txtValor.Text);
                        BE.dscto2 = VariablesPublicas.StringtoDecimal(txtDctos.Text);
                        BE.valorventa2 = VariablesPublicas.StringtoDecimal(txtVenta.Text);
                        BE.igv2 = VariablesPublicas.StringtoDecimal(txtIgv.Text);
                        BE.total2 = VariablesPublicas.StringtoDecimal(txtTotal.Text);
                        if (BE.tipcamb > 0)
                        {
                            BE.bruto1 = Math.Round(VariablesPublicas.StringtoDecimal(txtValor.Text) * BE.tipcamb, 2);
                            BE.dscto1 = Math.Round(VariablesPublicas.StringtoDecimal(txtDctos.Text) * BE.tipcamb, 2);
                            BE.valorventa1 = Math.Round(VariablesPublicas.StringtoDecimal(txtVenta.Text) * BE.tipcamb, 2);
                            BE.igv1 = Math.Round(VariablesPublicas.StringtoDecimal(txtIgv.Text) * BE.tipcamb, 2);
                            BE.total1 = Math.Round(VariablesPublicas.StringtoDecimal(txtTotal.Text) * BE.tipcamb, 2);

                            BE.valorventa1 = Math.Round(BE.valorventa1, 2);
                            BE.igv1 = Math.Round(BE.igv1, 2);
                            BE.total1 = Math.Round(BE.total1, 2);
                        }

                        break;
                }
                BE.valorventa1 = BE.valorventa1 + (BE.total1 - (BE.valorventa1 + BE.igv1)); // S/.
                BE.valorventa2 = BE.valorventa2 + (BE.total2 - (BE.valorventa2 + BE.igv2)); // US$

                BE.pdscto = 0;
                BE.pigv = VariablesPublicas.StringtoDecimal(txtPigv.Text);
                BE.tienda = "";
                BE.ndias = 0;
                BE.vendedorid = "";
                BE.porcvta = 0;
                BE.porcefect = 0;
                BE.vinculante = "";
                BE.usuar = VariablesPublicas.Usuar.ToUpper().Trim();
                BE.maqreg = xmaqreg;
                //BE.numdocfinal = xnumdocfinal;
                BE.numdocfinal = txtNumFin.Text;
                BE.estabsunat = xestabsunat;
                #endregion

                #region ****ingreso movimiento detalle***

                int item = 0;
                foreach (DataRow fila in DetFacturacion.Rows)
                {
                    Detalle = new tb_co_Ventas.Item();

                    item++;

                    Detalle.perianio = VariablesPublicas.perianio;
                    Detalle.perimes = VariablesPublicas.PADL(txtMes.Text.Trim(), 2, "0");
                    Detalle.moduloid = modulo.ToString();
                    Detalle.local = local.ToString();
                    Detalle.diarioid = BE.diarioid;
                    Detalle.asiento = VariablesPublicas.PADL(txtNumero.Text.Trim(), 6, "0");

                    //datos documento cabecera importante [todos]
                    Detalle.tipdoc = cboTipdoc.Text.Substring(0, 2);
                    Detalle.serdoc = txtSerie.Text.Trim().ToString().PadLeft(4, '0');
                    Detalle.numdoc = txtNumero.Text.Trim().ToString().PadLeft(10, '0');
                    Detalle.fechdoc = Convert.ToDateTime(fRegistro.Text.Trim());
                    if (fecVenc.ShowCheckBox)
                    {
                        Detalle.fechvcto = fecVenc.Value;
                    }
                    //datos de cliente o proveedor
                    Detalle.nmruc = txtRuc.Text.Trim().ToUpper();
                    Detalle.ctactename = txtCtactename.Text.Trim().ToUpper();
                    //accion del alamacen dependiendo del tipo de documento
                    Detalle.almacaccionid = fila["almacaccionid"].ToString();
                    if (chkActivo.Checked == true)
                    {
                        Detalle.status = activo;
                    }
                    if (chkActivo.Checked == false)
                    {
                        Detalle.status = anulad;
                    }
                    //datos documento de referencia
                    if (cboTipdocref.Enabled)
                    {
                        if (cboTipdocref.Text.Length > 0)
                        {
                            Detalle.tipref = cboTipdocref.Text.Substring(0, 2);
                        }
                        //Detalle.tipref = cboTipdocref.Text.Substring(0, 2);
                        Detalle.serref = txtSerieref.Text.Trim().ToString();
                        Detalle.numref = txtNumeroref.Text.Trim().ToString();
                        if (fechaRefer.ShowCheckBox)
                        {
                            Detalle.fechref = fechaRefer.Value;
                        }
                    }
                    //datos calculados de detalle de movimiento obtenidos de memoria
                    Detalle.items = fila["items"].ToString();
                    Detalle.asientoitems = item.ToString().PadLeft(5, '0');
                    Detalle.rubroid = fila["rubroid"].ToString();
                    Detalle.tippedido = fila["tippedido"].ToString();
                    Detalle.serpedido = fila["serpedido"].ToString();
                    Detalle.numpedido = fila["numpedido"].ToString();
                    Detalle.tipOp = fila["tip_op"].ToString();
                    Detalle.serOp = fila["ser_op"].ToString();
                    Detalle.numOp = fila["num_op"].ToString();
                    Detalle.productid = fila["productid"].ToString();
                    Detalle.productname = fila["productname"].ToString();
                    Detalle.tallacolor = fila["tallacolor"].ToString();
                    Detalle.unidmedidaid = fila["unidmedidaid"].ToString();
                    Detalle.cantidad = Convert.ToDecimal(fila["cantidad"].ToString());

                    switch (xMoneda)
                    {
                        case "1":
                            Detalle.precunit1 = Convert.ToDecimal(fila["precunit"].ToString());
                            Detalle.bruto1 = Convert.ToDecimal(fila["bruto"].ToString());
                            Detalle.dscto1 = Convert.ToDecimal(fila["dscto"].ToString());
                            Detalle.valorventa1 = Convert.ToDecimal(fila["valorventa"].ToString());
                            Detalle.igv1 = Convert.ToDecimal(fila["igvo"].ToString());
                            Detalle.total1 = Convert.ToDecimal(fila["total"].ToString());
                            if ((BE.tipcamb > 0))
                            {
                                Detalle.precunit2 = Math.Round(Convert.ToDecimal(fila["precunit"]) / BE.tipcamb, 2);
                                Detalle.bruto2 = Math.Round(Convert.ToDecimal(fila["bruto"]) / BE.tipcamb, 2);
                                Detalle.dscto2 = Math.Round(Convert.ToDecimal(fila["dscto"]) / BE.tipcamb, 2);
                                Detalle.valorventa2 = Math.Round(Convert.ToDecimal(fila["valorventa"]) / BE.tipcamb, 2);
                                Detalle.igv2 = Math.Round(Convert.ToDecimal(fila["igvo"]) / BE.tipcamb, 2);
                                Detalle.total2 = Math.Round(Convert.ToDecimal(fila["total"]) / BE.tipcamb, 2);
                                BE.valorventa2 = Math.Round(BE.valorventa2, 2);
                                BE.igv2 = Math.Round(BE.igv2, 2);
                                BE.total2 = Math.Round(BE.total2, 2);
                            }
                            break;
                        case "2":
                            Detalle.precunit2 = Convert.ToDecimal(fila["precunit"].ToString());
                            Detalle.bruto2 = Convert.ToDecimal(fila["bruto"].ToString());
                            Detalle.dscto2 = Convert.ToDecimal(fila["dscto"].ToString());
                            Detalle.valorventa2 = Convert.ToDecimal(fila["valorventa"].ToString());
                            Detalle.igv2 = Convert.ToDecimal(fila["igvo"].ToString());
                            Detalle.total2 = Convert.ToDecimal(fila["total"].ToString());
                            if ((BE.tipcamb > 0))
                            {
                                Detalle.precunit1 = Math.Round(Convert.ToDecimal(fila["precunit"]) * BE.tipcamb, 2);
                                Detalle.bruto1 = Math.Round(Convert.ToDecimal(fila["bruto"]) * BE.tipcamb, 2);
                                Detalle.dscto1 = Math.Round(Convert.ToDecimal(fila["dscto"]) * BE.tipcamb, 2);
                                Detalle.valorventa1 = Math.Round(Convert.ToDecimal(fila["valorventa"]) * BE.tipcamb, 2);
                                Detalle.igv1 = Math.Round(Convert.ToDecimal(fila["igvo"]) * BE.tipcamb, 2);
                                Detalle.total1 = Math.Round(Convert.ToDecimal(fila["total"]) * BE.tipcamb, 2);
                                Detalle.valorventa1 = Math.Round(BE.valorventa1, 2);
                                Detalle.igv1 = Math.Round(BE.igv1, 2);
                                Detalle.total1 = Math.Round(BE.total1, 2);
                            }
                            break;
                    }
                    //Detalle.precunit1 = Convert.ToDecimal(fila["precunit1"].ToString());
                    //Detalle.bruto1 = Convert.ToDecimal(fila["bruto1"].ToString());
                    //Detalle.dscto1 = Convert.ToDecimal(fila["dscto1"].ToString());
                    //Detalle.valorventa1 = Convert.ToDecimal(fila["valorventa1"].ToString());
                    //Detalle.igv1 = Convert.ToDecimal(fila["igv1"].ToString());
                    //Detalle.total1 = Convert.ToDecimal(fila["total1"].ToString());

                    Detalle.pdscto = Convert.ToDecimal(fila["pdscto"].ToString());
                    Detalle.pigv = Convert.ToDecimal(txtPigv.Text.Trim());
                    Detalle.tipguia = fila["tipguia"].ToString();
                    Detalle.serguia = fila["serguia"].ToString();
                    Detalle.numguia = fila["numguia"].ToString();

                    Detalle.afectoigvid = fila["afectoigvid"].ToString();
                    Detalle.incprec = chkIncluye.Checked;
                    Detalle.vendedorid = fila["vendedorid"].ToString();
                    Detalle.cencosid = fila["cencosid"].ToString();
                    Detalle.glosa = txtGlosa.Text.Trim().ToUpper().ToString();
                    Detalle.moneda = Equivalencias.Left(cboMoneda.SelectedValue.ToString(), 1);
                    Detalle.tcamb = Convert.ToDecimal(txtTipocambio.Text.Trim());
                    Detalle.ordencs = fila["ordencs"].ToString();
                    Detalle.comisionvta = Convert.ToDecimal(fila["comisionvta"].ToString());
                    Detalle.porcvta = Convert.ToDecimal(fila["porcvta"].ToString());
                    Detalle.porcefect = Convert.ToDecimal(fila["porcefect"].ToString());
                    Detalle.observ1 = fila["observ1"].ToString();
                    Detalle.observ2 = fila["observ2"].ToString();
                    Detalle.observ3 = fila["observ3"].ToString();
                    Detalle.observ4 = fila["observ4"].ToString();
                    Detalle.observ5 = fila["observ5"].ToString();
                    Detalle.precunit = Convert.ToDecimal(fila["precunit"].ToString());
                    Detalle.bruto = Convert.ToDecimal(fila["bruto"].ToString());
                    Detalle.dscto = Convert.ToDecimal(fila["dscto"].ToString());
                    Detalle.valorventa = Convert.ToDecimal(fila["valorventa"].ToString());
                    Detalle.igvo = Convert.ToDecimal(fila["igvo"].ToString());
                    Detalle.total = Convert.ToDecimal(fila["total"].ToString());

                    Detalle.valorventa = Detalle.valorventa + (Detalle.total - (Detalle.valorventa + Detalle.igvo)); // Origen
                    Detalle.valorventa1 = Detalle.valorventa1 + (Detalle.total1 - (Detalle.valorventa1 + Detalle.igv1)); // S/.
                    Detalle.valorventa2 = Detalle.valorventa2 + (Detalle.total2 - (Detalle.valorventa2 + Detalle.igv2)); // US$

                    Detalle.usuar = VariablesPublicas.Usuar;

                    ListaItems.Add(Detalle);
                }

                BE.ListaItems = ListaItems;
                #endregion

                #region **Save BD
                try
                {
                    if (u_n_opsel == 1)  //Si es nuevo
                    {
                        if (BL.Insert(VariablesPublicas.EmpresaID.ToString(), BE))
                        {
                            seguridadlog("N");
                            if (!nopideimpresion)
                            {
                                string message = "Desea Imprimir Documento Nro: " + local.ToString() + " " + VariablesPublicas.PADL(cboSubdiario.SelectedValue.ToString(), 4, "0") + "/" + txtMes.Text + "-" + txtAsiento.Text + " ...?";
                                string caption = "Impresión";
                                MessageBoxButtons buttons = MessageBoxButtons.YesNo;
                                DialogResult result;

                                // Muestra el cuadro de mensaje.
                                result = DevExpress.XtraEditors.XtraMessageBox.Show(this, message, caption, buttons, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
                                if (result == DialogResult.Yes)
                                {
                                    Accion(6, "", xnum);
                                }
                            }
                            tmptablacab = null;
                            tmptabladet = null;
                            U_CancelarEdicion(0);
                        }
                    }
                    else if (u_n_opsel == 2)  //Si NO es nuevo
                    {
                        if (BL.Update(VariablesPublicas.EmpresaID.ToString(), BE))
                        {
                            seguridadlog("M");
                            if (!nopideimpresion)
                            {
                                string message = "Desea Imprimir Documento Nro: " + local.ToString() + " " + VariablesPublicas.PADL(cboSubdiario.SelectedValue.ToString(), 4, "0") + "/" + txtMes.Text + "-" + txtAsiento.Text + " ...?";
                                string caption = "Impresión";
                                MessageBoxButtons buttons = MessageBoxButtons.YesNo;
                                DialogResult result;

                                // Muestra el cuadro de mensaje.
                                result = DevExpress.XtraEditors.XtraMessageBox.Show(this, message, caption, buttons, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
                                if (result == DialogResult.Yes)
                                {
                                    Accion(6, "", xnum);
                                }
                            }
                            tmptablacab = null;
                            tmptabladet = null;
                            U_CancelarEdicion(0);
                        }
                    }
                }
                catch (Exception ex)
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                #endregion
            }
        }
        private void CargaDatos()
        {
            string xnumero = "..";
            if (txtAsiento.Text.Trim().Length > 0)
            {
                xnumero = txtAsiento.Text;
            }
            if ((tmptablacab != null))
            {
                CabFacturacion = tmptablacab;
            }
            else
            {
                tb_co_VentascabBL BL = new tb_co_VentascabBL();
                tb_co_Ventascab BE = new tb_co_Ventascab();

                BE.perianio = VariablesPublicas.perianio;
                BE.perimes = txtMes.Text;
                BE.moduloid = modulo.ToString();//modulo.ToString();
                BE.local = local.ToString(); //local.ToString();
                BE.diarioid = cboSubdiario.SelectedValue.ToString();
                BE.asiento = xnumero;

                try
                {
                    CabFacturacion = BL.GetAll(VariablesPublicas.EmpresaID.ToString(), BE).Tables[0];
                }
                catch (Exception ex)
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            if ((tmptabladet != null))
            {
                DetFacturacion = tmptabladet;
            }
            else
            {
                //DetFacturacion = tmptabladet;
                tb_co_VentasdetBL BL = new tb_co_VentasdetBL();
                tb_co_Ventasdet BE = new tb_co_Ventasdet();

                BE.perianio = VariablesPublicas.perianio;
                BE.perimes = txtMes.Text;
                BE.moduloid = modulo.ToString();
                BE.local = local.ToString();
                BE.diarioid = cboSubdiario.SelectedValue.ToString();
                BE.asiento = xnumero;

                try
                {
                    DetFacturacion = BL.GetAll(VariablesPublicas.EmpresaID.ToString(), BE).Tables[0];
                }
                catch (Exception ex)
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            if ((CabFacturacion != null))
                if (CabFacturacion.Rows.Count > 0)
                {
                    decimal ximpodua = 0;
                    txtTipoventa.Text = CabFacturacion.Rows[0]["tipoventa"].ToString().Trim();
                    validaTipoVenta();
                    txtRuc.Text = CabFacturacion.Rows[0]["nmruc"].ToString().Trim();
                    ValidaProveedor();
                    // txtCtactename.Text = CabFacturacion.Rows[0]["ctactename"].ToString();
                    // Datos Aduanas
                    cboAduana.SelectedValue = CabFacturacion.Rows[0]["aduanaid"];
                    aduPeriodo.Text = CabFacturacion.Rows[0]["aniodua"].ToString().Trim();
                    aduCorrelativo.Text = CabFacturacion.Rows[0]["numdua"].ToString().Trim();
                    // aduValorfob.Text = System.String.Format(CabFacturacion.Rows[0]["valorfobdua"].ToString(), "###,###,###.00");
                    ximpodua = Convert.ToDecimal(CabFacturacion.Rows[0]["valorfobdua"]);
                    aduValorfob.Text = ximpodua.ToString("###,###,###.00");
                    if ((!object.ReferenceEquals(CabFacturacion.Rows[0]["fechembdua"], DBNull.Value)))
                    {
                        adufEmbarque.ShowCheckBox = true;
                        adufEmbarque.Value = Convert.ToDateTime(CabFacturacion.Rows[0]["fechembdua"]);
                    }
                    else
                    {
                        adufEmbarque.Value = DateTime.Now;
                        adufEmbarque.ShowCheckBox = false;
                    }
                    if ((!object.ReferenceEquals(CabFacturacion.Rows[0]["fechreguldua"], DBNull.Value)))
                    {
                        adufRegularizacion.ShowCheckBox = true;
                        adufRegularizacion.Value = Convert.ToDateTime(CabFacturacion.Rows[0]["fechreguldua"]);
                    }
                    else
                    {
                        adufRegularizacion.Value = DateTime.Now;
                        adufRegularizacion.ShowCheckBox = false;
                    } // FIn Datos Aduanas

                    //chkActivo.Checked = Convert.ToBoolean(CabFacturacion.Rows[0]["status"] = 1);
                    chkActivo.Checked = Convert.ToBoolean(CabFacturacion.Rows[0]["status"].ToString() == "0");
                    txtTipocambio.Text = CabFacturacion.Rows[0]["tipcamb"].ToString();
                    cboMoneda.SelectedValue = CabFacturacion.Rows[0]["moneda"].ToString();
                    if (cboMoneda.SelectedValue.ToString() == "1")
                    {
                        lblMoneda.Text = "S/.";
                        lblMoneda.ForeColor = Color.Blue;
                    }
                    else
                    {
                        lblMoneda.Text = "US$";
                        lblMoneda.ForeColor = Color.Green;
                    }

                    cboDestinoigv.SelectedValue = CabFacturacion.Rows[0]["afectoigvid"].ToString();

                    // cboOrigen.SelectedValue = CabFacturacion.Rows[0]["origen"].ToString();
                    switch (CabFacturacion.Rows[0]["origen"].ToString())
                    {
                        case "01":
                            cboOrigen.SelectedIndex = 0;
                            break;
                        case "02":
                            cboOrigen.SelectedIndex = 1;
                            break;
                    }
                    chkAfecto.Checked = Convert.ToBoolean(CabFacturacion.Rows[0]["afectoigv"].ToString());
                    chkIncluye.Checked = Convert.ToBoolean(CabFacturacion.Rows[0]["incprec"].ToString());
                    chkRetencion.Checked = Convert.ToBoolean(CabFacturacion.Rows[0]["afectretencion"].ToString());
                    // Datos Totalizados de Factura
                    totalizar();
                    // txtValor.Text = System.String.Format(CabFacturacion.Rows[0]["bruto1"].ToString(), "###,###,###.00");
                    // txtDctos.Text = System.String.Format(CabFacturacion.Rows[0]["dscto1"].ToString(), "###,###,###.00");
                    txtPigv.Text = String.Format(CabFacturacion.Rows[0]["pigv"].ToString(), "###.0");
                    // txtVenta.Text = System.String.Format(CabFacturacion.Rows[0]["valorventa1"].ToString(), "###,###,###.00");
                    // txtIgv.Text = System.String.Format(CabFacturacion.Rows[0]["igv1"].ToString(), "###,###,###.00");
                    // txtTotal.Text = System.String.Format(CabFacturacion.Rows[0]["total1"].ToString(), "###,###,###.00");
                    cboTipdoc.SelectedValue = CabFacturacion.Rows[0]["tipdoc"];
                    txtSerie.Text = CabFacturacion.Rows[0]["serdoc"].ToString().Trim();
                    txtNumero.Text = CabFacturacion.Rows[0]["numdoc"].ToString().Trim();
                    txtNumFin.Text = CabFacturacion.Rows[0]["numdocfinal"].ToString().Trim();
                    fRegistro.Value = Convert.ToDateTime(CabFacturacion.Rows[0]["fechdoc"]);
                    // lblTipoventa.Text = CabFacturacion.Rows[0]["dtipoventa"].ToString();
                    txtCtadetrac.Text = CabFacturacion.Rows[0]["nctadetraccion"].ToString().Trim();
                    txtGlosa.Text = CabFacturacion.Rows[0]["glosa"].ToString().Trim();
                    txtNumeroorden.Text = CabFacturacion.Rows[0]["ordencompra"].ToString().Trim();
                    // txtglosa2.Text = CabFacturacion.Rows(0).Item("glob_3");

                    cboTipdocref.SelectedValue = CabFacturacion.Rows[0]["tipref"];
                    txtSerieref.Text = CabFacturacion.Rows[0]["serref"].ToString().Trim();
                    txtNumeroref.Text = CabFacturacion.Rows[0]["numref"].ToString().Trim();

                    cboServicio.SelectedValue = CabFacturacion.Rows[0]["detraccionid"];

                    _terminoventa = CabFacturacion.Rows[0]["terminovta"].ToString().Trim();
                    _pais = CabFacturacion.Rows[0]["dpais"].ToString().Trim();
                    _embarque = CabFacturacion.Rows[0]["embarcador"].ToString().Trim();
                    _condpago = CabFacturacion.Rows[0]["condicionpago"].ToString().Trim();
                    _cartacredito = CabFacturacion.Rows[0]["cartacredito"].ToString().Trim();
                    _codigovia = CabFacturacion.Rows[0]["viaembarque"].ToString().Trim();
                    _referencia = CabFacturacion.Rows[0]["referencia"].ToString().Trim();

                    txtPorcdet.Text = System.String.Format(CabFacturacion.Rows[0]["porcdetraccion"].ToString(), "###.00");
                    if ((!object.ReferenceEquals(CabFacturacion.Rows[0]["fechvcto"], DBNull.Value)))
                    {
                        fecVenc.Value = Convert.ToDateTime(CabFacturacion.Rows[0]["fechvcto"]);
                        fecVenc.ShowCheckBox = true;
                    }
                    else
                    {
                        fecVenc.ShowCheckBox = false;
                    }

                    if ((!object.ReferenceEquals(CabFacturacion.Rows[0]["fechref"], DBNull.Value)))
                    {
                        fechaRefer.Value = Convert.ToDateTime(CabFacturacion.Rows[0]["fechref"]);
                        fechaRefer.ShowCheckBox = true;
                    }
                    else
                    {
                        fechaRefer.ShowCheckBox = false;
                    }
                    xmaqreg = CabFacturacion.Rows[0]["maqreg"].ToString().Trim();
                    xnumdocfinal = CabFacturacion.Rows[0]["numdocfinal"].ToString().Trim();
                    xestabsunat = CabFacturacion.Rows[0]["estabsunat"].ToString().Trim();
                }
                else
                {
                    blanquear(false);
                }
            GridExaminar.AutoGenerateColumns = false;
            int LC_CONT;
            for (LC_CONT = 0; LC_CONT <= GridExaminar.ColumnCount - 1; LC_CONT++)
            {
                GridExaminar.Columns[LC_CONT].SortMode = DataGridViewColumnSortMode.NotSortable;
            }
            GridExaminar.DataSource = DetFacturacion;
            PintaEncabezados(GridExaminar);
            if ((CabFacturacion != null))
            {
                if (CabFacturacion.Rows.Count > 0)
                {
                    lblAnulado.Text = (chkActivo.Checked ? "" : "ANULADO");
                    lblUsuar.Text = CabFacturacion.Rows[0]["Usuar"].ToString().ToUpper().Trim() + " - " + CabFacturacion.Rows[0]["feact"].ToString().Trim();
                }
            }
            else
            {
                lblAnulado.Text = "";
                lblUsuar.Text = "";
            }
            u_ShowGets();
        }
        public void U_CargaDatos()
        {
            string xvmtipocompra = "";
            if (cboTipoventa.Enabled)
            {
                if ((cboTipoventa.SelectedValue != null))
                {
                    xvmtipocompra = cboTipoventa.SelectedValue.ToString();
                }
            }
            string xpalabra1 = "";
            string xpalabra2 = "";
            string xpalabra3 = "";
            string xpalabra4 = "";
            string xtipdoc = "";
            if (txtGlosa.Enabled)
            {
                xpalabra1 = VariablesPublicas.Palabras(txtGlosa.Text.Trim(), 1);
                xpalabra2 = VariablesPublicas.Palabras(txtGlosa.Text.Trim(), 2);
                xpalabra3 = VariablesPublicas.Palabras(txtGlosa.Text.Trim(), 3);
                xpalabra4 = VariablesPublicas.Palabras(txtGlosa.Text.Trim(), 4);
            }
            if (cboTipdoc.Enabled)
            {
                xtipdoc = cboTipdoc.SelectedValue.ToString();
            }
            string xnumdoc = "";
            string xserdoc = "";
            if (txtNumdocu.Enabled)
            {
                xserdoc = Equivalencias.Left(txtNumdocu.Text, 4);
                xnumdoc = Equivalencias.Right(txtNumdocu.Text, 10);
            }

            string xfechaini = "";
            string xfechafin = "";
            string xdetalle = "";
            if (Fechaini.Enabled)
            {
                xfechaini = Convert.ToDateTime(Fechaini.Text).ToString();
            }
            if (Fechafin.Enabled)
            {
                xfechafin = Convert.ToDateTime(Fechafin.Text).ToString();
            }
            string xcodmes = "";
            if (txtRegmes.Enabled)
            {
                xcodmes = txtRegmes.Text;
            }
            else
            {
                xcodmes = _Mes;
            }
            if (txtDetalle.Enabled)
            {
                xdetalle = txtDetalle.Text;
            }
            string xorigen = "";
            if (cboOrigen.Enabled)
            {
                if ((cboOrigen.Text.Substring(0, 2) != ""))
                {
                    xorigen = cboOrigen.Text.Substring(0, 2);
                }
            }
            btnRefrescar.Enabled = false;
            try
            {
                tb_co_VentascabBL BL = new tb_co_VentascabBL();
                tb_co_Ventascab BE = new tb_co_Ventascab();

                BE.perianio = VariablesPublicas.perianio;
                BE.perimes = xcodmes;
                //BE.diarioid = cboSubdiario.Text.Substring(0, 4);
                //BE.asiento = txtAsiento.Text;
                BE.nmruc = xdetalle;
                BE.tipdoc = xtipdoc;
                BE.origen = xorigen;
                BE.serdoc = xserdoc;
                BE.numdoc = xnumdoc;
                BE.tipoventa = xvmtipocompra;
                BE.glosa = xpalabra1;

                tabla = BL.GetAll(VariablesPublicas.EmpresaID.ToString(), BE).Tables[0];
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            //tabla = ocapa.spu_AyudaRegVentas(GlobalVars.GetInstance.Company, GlobalVars.GetInstance.Periodo, xcodmes, "", xfechaini, xfechafin, xdetalle, xpalabra1, xpalabra2, xpalabra3, xorigen, xnumdoculike, xtipdoc, xvmtipocompra);
            btnRefrescar.Enabled = true;
            //if (ocapa.sql_error.Length > 0)
            //{
            //    sw_Load = false;
            //    frmclass.ShowError(ocapa.sql_error, this);
            //}
            //else
            //{
                SortOrder sorted = default(SortOrder);
                string xnomcolumna = "";
                if ((dgProveedor.SortedColumn != null))
                {
                    xnomcolumna = dgProveedor.Columns[dgProveedor.SortedColumn.Index].Name;
                    sorted = dgProveedor.SortOrder;
                }
                dgProveedor.AutoGenerateColumns = false;
                dgProveedor.DataSource = tabla;
                dgProveedor.AllowUserToResizeRows = false;
                if (xnomcolumna.Trim().Length > 0)
                {
                    if (sorted == SortOrder.Ascending)
                    {
                        dgProveedor.Sort(dgProveedor.Columns[xnomcolumna], System.ComponentModel.ListSortDirection.Ascending);
                    }
                    else
                    {
                        dgProveedor.Sort(dgProveedor.Columns[xnomcolumna], System.ComponentModel.ListSortDirection.Descending);

                    }
                }
                else
                {
                    dgProveedor.Sort(dgProveedor.Columns["fechdoc"], System.ComponentModel.ListSortDirection.Descending);
                }
                if (dgProveedor.Rows.Count > 0)
                {
                    dgProveedor.CurrentCell = dgProveedor.Rows[0].Cells["asiento"];
                    dgProveedor.Focus();
                    dgProveedor.BeginEdit(true);
                }
                pintar();
            //}
        }