protected void btnEditar_Click(object sender, EventArgs e)
        {
            oThread = new Thread(delegate() { Esperar(1000); });
            oThread.Start();

            clsOperaciones lstOperaciones = new clsOperaciones();
            clsDetOperacion lstDetOperacion = new clsDetOperacion();

            Operaciones Operacion = new Operaciones();
            DocumenOperacion DocumenOpe = new DocumenOperacion();
            DataTable dtDetOperacion;
            int nOpeCod = 0;
            int nDopCod = 0;
            string cDopDescri = "";

            try
            {
                HabilitarCampos(true);
                CargarCombos();
                CargarClientes();
                CargarTransportistas();
                CargarVendedores();

                txtDireccion.Enabled = false;
                txtDocCli.Enabled = false;
                txtTelefono.Enabled = false;

                nOpeCod = int.Parse(dgvListOperVentas.Rows[dgvListOperVentas.SelectedIndex].Cells[2].Text);

                SetPanelDocumento(nOpeCod);
                nDopCod = int.Parse(dgvDocumentos.Rows[0].Cells[1].Text);
                cDopDescri = dgvDocumentos.Rows[0].Cells[2].Text;

                CargarCamposOperacion(nOpeCod);
                CargarCamposDocumento(nDopCod, cDopDescri);
                ddlClientes_SelectedIndexChanged(sender, e);

                dtDetOperacion = lstDetOperacion.GetListDetOperacion(nOpeCod);
                g_dtDetOperacion = dtDetOperacion;
                RellenarGrilla(ref dgvDetalleVenta, dtDetOperacion, nNroDetPed);

                lblProceso.Value = lblOpeEstado.Value == "C" ? "CLOSE" : "EDIT";
                SetBotones(lblProceso.Value);

                GuardarDtCabeceraDocumento();
                oThread.Join();

            }
            catch (Exception ex)
            {
                oThread.Abort();
                MessageBox("Error Interno: " + ex.Message);
            }
        }
        protected void btnGuardar_Click(object sender, EventArgs e)
        {
            String cfecLetra , ctipago;
            cfecLetra = txtFecha.Text;
            int nPrvCod = Convert.ToInt32(hdcodper.Value);
            if (rbtdias.Checked)
                ctipago = "D";
            else
                ctipago = "L";
            int cuotas = int.Parse(txtNumCuotas.Text);
            int icodigo, idetcodigo;
            Double monto_total = Double.Parse(lbpago.Text);
            Double monto_nota = Double.Parse(lbresta.Text);
            String moneda;
            moneda = ddlMoneda_new.SelectedValue;
            try
            {
                clsLetra _Letra = new clsLetra();
                letra obj = new letra();
                icodigo = Convert.ToInt32(_Letra.MaxOpeCod() + 1);
                obj.icodigo = icodigo;
                obj.itotcuota = cuotas;
                obj.nmontocuota = Convert.ToDecimal(monto_total);
                obj.cmoneda = moneda;
                obj.nintpag = Convert.ToDecimal(0.00);
                obj.iestado = "1";
                obj.dfeccreacion = Convert.ToDateTime(cfecLetra);
                obj.dfecmod = DateTime.Today;
                obj.ctippago = ctipago;
                obj.nmntnota = Convert.ToDecimal(monto_nota);
                _Letra.fnletraInsertar(obj);
                clsdetletra _detletra = new clsdetletra();

                foreach (GridViewRow row in dgvcuotas.Rows)
                {
                    det_letra _detobj = new det_letra();
                    _detobj.icodletra = icodigo;
                    _detobj.inumletra = Convert.ToInt32(row.Cells[0].Text);
                    TextBox num_let = row.FindControl("num_let") as TextBox;
                    _detobj.cnumletra = num_let.Text;
                    TextBox ccodletra = row.FindControl("cod_unic") as TextBox;
                    _detobj.ccodletra = ccodletra.Text;
                    TextBox monto = row.FindControl("monto") as TextBox;
                    _detobj.nmonto = Convert.ToDecimal(monto.Text);
                    _detobj.cestado = "1";
                    _detobj.ninteres = Convert.ToDecimal(0.00);
                    TextBox txtFecVen = row.FindControl("txtFecVen") as TextBox;
                    _detobj.dfecvenc = Convert.ToDateTime(txtFecVen.Text);
                    _detobj.dfecmod = DateTime.Today;
                    idetcodigo = Convert.ToInt32(_detletra.Maxdetletra_cod()) + 1;
                    _detobj.idetletra = idetcodigo;
                    _detletra.fndet_letraInsertar(_detobj);
                }
                clsDocumenOperacion _docobj = new clsDocumenOperacion();
                DocumenOperacion _docope = new DocumenOperacion();
                Int64 cod_fact;
                foreach (GridViewRow row in dgvListFact.Rows)
                {

                    CheckBox check = row.FindControl("CheckBox1") as CheckBox;
                    if (check.Checked)
                    {
                        cod_fact = Convert.ToInt64(row.Cells[2].Text);
                        //_docope = _docobj.GetListOperaciones(cod_fact );
                        _docope = _docobj.GetDocumenOperaciona(cod_fact);

                        _docope.icodletra = icodigo;
                        _docobj.fnDocOpeUpdate(_docope);
                    }
                }
                Int32 cod_not;
                clsOpeNotas _formnot = new clsOpeNotas();
                Notas _docopenot = new Notas();
                rel_notfactura _relacion = new rel_notfactura();
                clsrel_notfactura _formrel = new clsrel_notfactura();
                dgvNotas.Columns[3].Visible = true;
                dgvNotas.Columns[5].Visible = true;
                foreach (GridViewRow row in dgvNotas.Rows)
                {

                    CheckBox check = row.FindControl("grdchknota") as CheckBox;
                    if (check.Checked)
                    {
                        cod_not = Convert.ToInt32(row.Cells[5].Text);
                        //clsOpeNotas
                        _docopenot = _formnot.GetNota(cod_not);
                        _docopenot.cestadoNota = "V";
                        _docopenot.nmntutilizado = _docopenot.nmontoNota;
                        _formnot.fnNotaUpdate(_docopenot);

                        _relacion.idtpcod = icodigo;
                        _relacion.inota = cod_not;
                        _relacion.nmonto = _docopenot.nmontoNota;
                        _relacion.dfecmod = DateTime.Today;
                        //_relacion .iusrcrc
                        _relacion.irelnotfac = Convert.ToInt32(_formrel.MaxOpeCod()) + 1;
                        _formrel.fnNotaInsert(_relacion);
                    }
                }
                dgvNotas.Columns[3].Visible = false;
                dgvNotas.Columns[5].Visible = false;
                IniciarCampos();

                obj = _Letra.GetLetra(icodigo);
                obj.iestado = "1";
                _Letra.fnletraupdate(obj);
                pnBusqueda.Visible = true;
                pnNuevo.Visible = false;
                IniciarCampos();
                btnProcesar_Click(sender, e);
            }
            catch (Exception ex)
            {
                MessageBox("Error Interno: " + ex.Message);
            }
        }
        protected void GuardarDtCabeceraDocumento()
        {
            DocumenOperacion DocumenOpe = new DocumenOperacion();
            clsDocumenOperacion lstDocumenOpe = new clsDocumenOperacion();
            DataTable dtCabeceraOperacion = CreatDTCabeceraVenta();

            int OpeCod = int.Parse(lblNroPedido.Text);
            string NroGuia = "";
            string NroPedido = "";

            DocumenOpe = lstDocumenOpe.GetDocumenOperacion(OpeCod, 2);
            if (DocumenOpe != null)
            {
                NroGuia = DocumenOpe.dopNroSerie.ToString() + " - " + DocumenOpe.dopNumero.ToString();
            }
            DocumenOpe = lstDocumenOpe.GetDocumenOperacion(OpeCod, 4);
            if (DocumenOpe != null)
            {
                NroPedido = DocumenOpe.dopNroSerie.ToString() + " - " + DocumenOpe.dopNumero.ToString();
            }

            DataRow newRow = dtCabeceraOperacion.NewRow();
            newRow["cRazonSocial"] = ddlClientes.SelectedItem.Text;
            newRow["cDireccion"] = txtDireccion.Text;
            newRow["cTelefono"] = txtTelefono.Text;
            newRow["cNroGuia"] = NroGuia;
            newRow["cNroPedido"] = NroPedido;
            newRow["cRuc"] = txtDocCli.Text;
            newRow["cFormaPago"] = ddlTipoVenta.SelectedItem.Text;
            newRow["cAnio"] = DateTime.Parse(txtFecha.Text).Year.ToString();
            newRow["cMes"] = DateTime.Parse(txtFecha.Text).Month.ToString();
            newRow["cDia"] = DateTime.Parse(txtFecha.Text).Day.ToString();
            newRow["cValorVenta"] = SetFormatNum(GetNumero(txtValorVenta.Text) -GetNumero(txtDescuento.Text));
            newRow["cFlete"] = txtFlete.Text;
            newRow["cIGV"] = txtIgv.Text;
            newRow["cTotal"] = txtTotal.Text;
            newRow["cTotalSinFlete"] = SetFormatNum(GetNumero(newRow["cValorVenta"].ToString()) * (nTasIGV+1));
            newRow["cTotalLetras"] = ConvertiraLetras(decimal.Parse((txtTotal.Text.Replace("S/.", "").Trim()).Replace("$", "").Trim()));
            newRow["Destinatario"] = "";
            newRow["PLlegada"] = "";
            newRow["NroFactura"] = "";
            newRow["Unidad"] = "";

            dtCabeceraOperacion.Rows.Add(newRow);
            AgregarVariableSession("dtCabeceraOperacion", dtCabeceraOperacion);
        }
        private void CargarCamposDocumento(int _dopCod, string cDopDescri)
        {
            clsDocumenOperacion lstDocumenOpe = new clsDocumenOperacion();
            DocumenOperacion DocumenOpe = new DocumenOperacion();

            try
            {
                DocumenOpe = lstDocumenOpe.GetDocumenOperacion(_dopCod);

                lblTipoDoc.Value = ddlTipoDocu.SelectedValue;
                lblDescriDocumento.Text = cDopDescri;

                lblTipoDoc.Value = DocumenOpe.tdoCod.ToString();
                lbldopCod.Value = DocumenOpe.dopCod.ToString();
                lblNroDocumento.Text = DocumenOpe.dopNroSerie.ToString() + " - " + DocumenOpe.dopNumero.ToString();
                txtFecha.Text = ((DateTime)DocumenOpe.dopFecEmision).ToString("yyyy-MM-dd");

                switch (lblTipoDoc.Value)
                {
                    case "2":
                        btnImprimir.OnClientClick = "AbrirVentanaGuia()";
                        break;
                    case "4":
                        btnImprimir.OnClientClick = "AbrirVentanaNota()";
                        break;
                    case "5":
                        btnImprimir.OnClientClick = "AbrirVentanaBoleta()";
                        break;
                    default:
                        btnImprimir.OnClientClick = "AbrirVentanaFactura()";
                        break;
                }
            }
            catch (Exception ex)
            {
                MessageBox("Error Interno: " + ex.Message);
            }
        }
 /// <summary>
 /// Método desusado para agregar un nuevo objeto al EntitySet DocumenOperacion. Considere la posibilidad de usar el método .Add de la propiedad ObjectSet&lt;T&gt; asociada.
 /// </summary>
 public void AddToDocumenOperacion(DocumenOperacion documenOperacion)
 {
     base.AddObject("DocumenOperacion", documenOperacion);
 }
 /// <summary>
 /// Crear un nuevo objeto DocumenOperacion.
 /// </summary>
 /// <param name="dopCod">Valor inicial de la propiedad dopCod.</param>
 /// <param name="opeCod">Valor inicial de la propiedad OpeCod.</param>
 /// <param name="tdoCod">Valor inicial de la propiedad tdoCod.</param>
 public static DocumenOperacion CreateDocumenOperacion(global::System.Int64 dopCod, global::System.Int64 opeCod, global::System.Int32 tdoCod)
 {
     DocumenOperacion documenOperacion = new DocumenOperacion();
     documenOperacion.dopCod = dopCod;
     documenOperacion.OpeCod = opeCod;
     documenOperacion.tdoCod = tdoCod;
     return documenOperacion;
 }
        protected void btnProcesar_Click(object sender, EventArgs e)
        {
            string cMensaje = "";
            clsOperaciones lstOperaciones = new clsOperaciones();

            long ndopCod = 0;
            int ntcmCod = 0;
            try
            {
                if (ValidarDatos("OPE", ref cMensaje,"PROC"))
                {
                    if (lblProceso.Value == "NEW")
                    {
                        txtFleteTra.Text = Math.Round(GetNumero(txtSubTotal.Text) / 100, 2).ToString();
                        txtFlete.Text = SetFormatNum(Math.Round(GetNumero(txtSubTotal.Text) / 100, 2));
                        long nOpeCod = lstOperaciones.MaxOpeCod() + 1;
                        lblNroPedido.Text = nOpeCod.ToString().PadLeft(10, '0');
                        txtDesEspec.Text = "0.0";
                    }

                    lstOperaciones.Procesar(this, gcOpeTipo, ref ndopCod, ref ntcmCod);
                    lbldopCod.Value = ndopCod.ToString();
                    lbltcmCod.Value = ntcmCod.ToString();
                    lblOpeEstado.Value = "P";
                    bDetallesChanged = 0;

                    GuardarDtCabeceraDocumento();
                    MessageBox("La Operacion fue Procesada con Exito, Ahora puede imprimir.");
                    //NUEVO:  asigna funcion a botón IMPRIMIR
                    AsignarFuncionBotonImprimir();

                    lblProceso.Value = "EDIT";
                    SetBotones(lblProceso.Value);

                    ConfigurarDocumento();
                     /*generacion automatica de  la letra*/
                    string valor = lblTipoDoc.Value;
                    if (valor == "3" && ddlTipCiclo.SelectedValue == "D" && chkletra.Checked == true)
                    {
                        int cuotas = 1;
                        int icodigo, idetcodigo;
                        Double monto_total = Double.Parse(txtTotal.Text.ToString().Substring(3));
                        Double monto_nota = 0.00;
                        String moneda;
                        try
                        {
                            clsLetra _Letra = new clsLetra();
                            letra obj = new letra();

                            icodigo = Convert.ToInt32(_Letra.MaxOpeCod() + 1);
                            obj.icodigo = icodigo;
                            moneda = ddlMoneda.SelectedValue;
                            obj.icodigo = icodigo;
                            obj.itotcuota = cuotas;
                            obj.nmontocuota = Convert.ToDecimal(monto_total);
                            obj.cmoneda = moneda;
                            obj.nintpag = Convert.ToDecimal(0.00);
                            obj.iestado = "1";
                            obj.dfeccreacion = DateTime.Today;
                            obj.dfecmod = DateTime.Today;
                            obj.ctippago = "D";
                            obj.nmntnota = Convert.ToDecimal(monto_nota);
                            _Letra.fnletraInsertar(obj);
                            clsdetletra _detletra = new clsdetletra();
                            det_letra _detobj = new det_letra();
                            _detobj.icodletra = icodigo;
                            _detobj.inumletra = 1;
                            _detobj.cnumletra = "-";
                            _detobj.ccodletra = "-";
                            _detobj.nmonto = Convert.ToDecimal(monto_total);
                            _detobj.cestado = "1";
                            _detobj.ninteres = Convert.ToDecimal(0.00);
                            _detobj.dfecvenc = Convert.ToDateTime(txtFecha.Text).AddDays(Convert.ToInt16(this.txtCiclo.Text));
                            _detobj.dfecmod = DateTime.Today;
                            idetcodigo = Convert.ToInt32(_detletra.Maxdetletra_cod()) + 1;
                            _detobj.idetletra = idetcodigo;
                            _detletra.fndet_letraInsertar(_detobj);

                            clsDocumenOperacion _docobj = new clsDocumenOperacion();
                            DocumenOperacion _docope = new DocumenOperacion();
                            _docope = _docobj.GetDocumenOperaciona(dopcod_letra);
                            _docope.icodletra = icodigo;
                            _docobj.fnDocOpeUpdate(_docope);

                        }
                        catch (Exception ex)
                        {
                            MessageBox("Error Interno: " + ex.Message);
                        }

                    }
                }
                else
                {
                    MessageBox(cMensaje);
                }
            }
            catch (Exception ex)
            {
                MessageBox("Error Interno: " + ex.Message + ex.InnerException.Message);
            }
        }
        private void CargarCamposDocumento(int _dopCod, string cDopDescri)
        {
            clsDocumenOperacion lstDocumenOpe = new clsDocumenOperacion();
            DocumenOperacion DocumenOpe = new DocumenOperacion();

            try
            {
                DocumenOpe = lstDocumenOpe.GetDocumenOperacion(_dopCod);

                lblTipoDoc.Value = ddlTipoDocu.SelectedValue;
                lblDescriDocumento.Text = cDopDescri;

                lblTipoDoc.Value = DocumenOpe.tdoCod.ToString();
                lbldopCod.Value = DocumenOpe.dopCod.ToString();
                lblNroDocumento.Text = DocumenOpe.dopNroSerie.ToString() + " - " + DocumenOpe.dopNumero.ToString();
                txtFecha.Text = ((DateTime)DocumenOpe.dopFecEmision).ToString("yyyy-MM-dd");

                if (DocumenOpe.dopFecTraslado != null)
                    txtFecTraslado.Text = ((DateTime)DocumenOpe.dopFecTraslado).ToString("yyyy-MM-dd");
                else
                    txtFecTraslado.Text = ((DateTime)DocumenOpe.dopFecEmision).ToString("yyyy-MM-dd");

                if (DocumenOpe.dopPunPartida != null)
                    txtPuntoPartida.Text = DocumenOpe.dopPunPartida;
                else
                    txtPuntoPartida.Text = "";

                ConfigurarDocumento();
                GuardarDtCabeceraDocumento();
            }
            catch (Exception ex)
            {
                MessageBox("Error Interno: " + ex.Message);
            }
        }
        protected void GuardarDtCabeceraDocumento()
        {
            DocumenOperacion DocumenOpe = new DocumenOperacion();
            clsDocumenOperacion lstDocumenOpe = new clsDocumenOperacion();
            DataTable dtCabeceraOperacion = CreatDTCabeceraVenta();

            int OpeCod = int.Parse(lblNroPedido.Text);

            string NroGuia = "", NroFactura = "", moneda = "", NroPedido = "", cPuntoPartida = "", cFecTraslado = "", cFormaPago = "";

            DocumenOpe = lstDocumenOpe.GetDocumenOperacion(OpeCod, 3);
            if (DocumenOpe != null)
            {

                NroFactura = DocumenOpe.dopNroSerie.ToString() + " - " + DocumenOpe.dopNumero.ToString();
                //////////////////////cmbios silvia///////////////////////////
                dopcod_letra = Convert.ToInt32(DocumenOpe.dopCod);
                /////////////////////////////////////////////////////////////
            }
            DocumenOpe = lstDocumenOpe.GetDocumenOperacion(OpeCod, 2);
            if (DocumenOpe != null)
            {
                NroGuia = DocumenOpe.dopNroSerie.ToString() + " - " + DocumenOpe.dopNumero.ToString();
                if (DocumenOpe.dopPunPartida != null)
                    cPuntoPartida = DocumenOpe.dopPunPartida;
                if (DocumenOpe.dopFecTraslado != null)
                    cFecTraslado = ((DateTime)DocumenOpe.dopFecTraslado).ToString("yyyy-MM-dd");
                else
                    cFecTraslado = ((DateTime)DocumenOpe.dopFecEmision).ToString("yyyy-MM-dd");

            }

            if (txtOpeOrdCompra.Text != "")
                NroPedido = txtOpeOrdCompra.Text;
            else
            {
                DocumenOpe = lstDocumenOpe.GetDocumenOperacion(OpeCod, 4);
                if (DocumenOpe != null)
                {
                    NroPedido = DocumenOpe.dopNroSerie.ToString() + " - " + DocumenOpe.dopNumero.ToString();

                }
            }

            if (ddlMoneda.SelectedValue == "PEN")
                moneda = " Nuevos Soles";
            else
                moneda = " Dolares";

            if (ddlTipoVenta.SelectedValue == "CR")
                cFormaPago = txtCiclo.Text + " " +  ddlTipCiclo.SelectedItem.Text;
            else
                cFormaPago = ddlTipoVenta.SelectedItem.Text;

            DataRow newRow = dtCabeceraOperacion.NewRow();
            newRow["cRazonSocial"] = ddlClientes.SelectedItem.Text;
            newRow["cDireccion"] = txtDireccion.Text;
            newRow["cTelefono"] = txtTelefono.Text;
            newRow["cNroGuia"] = NroGuia;
            newRow["cNroPedido"] = NroPedido;
            newRow["cRuc"] = txtDocCli.Text;
            newRow["cFormaPago"] = cFormaPago;
            newRow["cSimboloMon"] = ddlMoneda.SelectedValue == "PEN" ? "S/." : "$";
            newRow["cAnio"] = DateTime.Parse(txtFecha.Text).Year.ToString();
            newRow["cMes"] = DateTime.Parse(txtFecha.Text).Month.ToString();
            newRow["cDia"] = DateTime.Parse(txtFecha.Text).Day.ToString();
            newRow["cValorVenta"] = (GetNumero(txtValorVenta.Text, false) - GetNumero(txtDescuento.Text, false)).ToString("F2");
            newRow["cFlete"] = GetNumero(txtFlete.Text, false).ToString("F2");
            newRow["cIGV"] = GetNumero(txtIgv.Text, false).ToString("F2");
            newRow["cTotal"] = GetNumero(txtTotal.Text, false).ToString("F2");
            newRow["cTotalSinFlete"] = SetFormatNum(GetNumero(newRow["cValorVenta"].ToString()) * (nTasIGV + 1));
            newRow["cTotalLetras"] = ConvertiraLetras(decimal.Parse((txtTotal.Text.Replace("S/.", "").Trim()).Replace("$", "").Trim())).ToUpper() + moneda.ToUpper();
            newRow["Destinatario"] = ddlClientes.SelectedItem.Text;
            newRow["PLlegada"] = txtDireccion.Text;
            newRow["NroFactura"] = NroFactura;
            newRow["Unidad"] = "";
            newRow["PPartida"] = cPuntoPartida;
            newRow["dFecTraslado"] = cFecTraslado;
            if (ddlTipoVenta.SelectedValue == "CR")
            {
                newRow["dOpeTipCiclo"] = ddlTipCiclo.SelectedItem.Text;
                newRow["dOpeCiclo"] = txtCiclo.Text;
            }
            else
            {
                newRow["dOpeTipCiclo"] = "";
                newRow["dOpeCiclo"] = "";
            }

            dtCabeceraOperacion.Rows.Add(newRow);
            AgregarVariableSession("dtCabeceraOperacion", dtCabeceraOperacion);
        }