Problema ao realizar o filtro de consulta
Pessoal eu sou iniciante na programação, e irei detalhar todo o processo resumidamente que estou fazendo no momento. Eu tenho uma pagina web que realiza uma consulta através de uma determinada data. Tenho um dropdow e dentro dele eu tenho a Opção Mês base e Período, caso eu selecione o Mês base devo carregar um campo de data informando o mes e o ano e em seguida eu tenho dois radio button escrito a opção Sim e Não e caso escolho fazer o filtro por periodo, deverei carregar um capo de data automaticamente para informar um determinado periodo preenchendo a data de inicio dd/MM/yyyy até a data final dd/MM/yyyy, após escolher Mês base ou por Período dentro do dropDow e carregar o campo de data automaticamente onde o usuário informará a data, consequentemente o mesmo irá escolher se a opção é de Liberação Sim ou Não (radio button) acho que é assim que se escreve rs, caso ele realiza sua escolha, deverá carregar os seguintes dados na grid:
AnoMêsBase, inscEstadual, razaoSocial e NME_ABREV.
Observação: No meu banco de dados a coluna AnoMesBase está dessa forma por exemplo 032018, sempre irá vir dessa forma, a data nunca será formatado o campo.
Porém não estou conseguindo trazer as informações que está no banco de dados.
Até agora implementei as seguintes classes:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate.Mapping.Attributes;
namespace Dominio.Domain
{
[Serializable]
[Class(Table = "DAP_EMPRESA", NameType = typeof(Empresa), Lazy = false)]
public class Empresa
{
private int codigo;
private string inscEstadual;
private string razaoSocial;
private string nomeAbreviado;
private DateTime dataCadastro;
private string cnpj;
[Id(Column = "ID_EMPRESA", Name = "Codigo", Generator = "increment", UnsavedValue = "0")]
public int Codigo
{
get { return codigo; }
set { codigo = value; }
}
[Property(Column = "INSC_ESTADUAL", Lazy = false)]
public string InscEstadual
{
get { return inscEstadual; }
set { inscEstadual = value; }
}
[Property(Column = "RAZAO_SOCIAL", Lazy = false)]
public string RazaoSocial
{
get { return razaoSocial; }
set { razaoSocial = value; }
}
[Property(Column = "NME_ABREV", Lazy = false)]
public string NomeAbreviado
{
get { return nomeAbreviado; }
set { nomeAbreviado = value; }
}
[Property(Column = "DAT_CADASTRO", Lazy = false)]
public DateTime DataCadastro
{
get { return dataCadastro; }
set { dataCadastro = value; }
}
[Property(Column = "CNPJ", Lazy = false)]
public string Cnpj
{
get { return cnpj; }
set { cnpj = value; }
}
}
}
using NHibernate.Mapping.Attributes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Dominio.Domain
{
[Serializable]
[Class(Table = "DAP_FINANCIAMENTO", NameType = typeof(Financiamento), Lazy = false)]
public class Financiamento
{
private int codigo; //
private Empresa empresa; //
private decimal vlrFinanciamento;//
private string inscEstadual;//
private string anoMesBase; //
private string anoMesFaturamento; //
private decimal vlrICMSPrevisto; //
private decimal totalRecolhimento; //
private DateTime datUltimoRecolhimento; //
private decimal totalLiberacao; //
private DateTime datLiberacao; //
private DateTime datUltimaLiberacao; //
private decimal totalDevolucao; //
private string descObservacao; //
private DateTime dataDevolucao; //
private DateTime dataCadastramento; //
private int mesBase; //
private int mesFat; //
[Id(Column = "ID_FINANCIAMENTO", Name = "Codigo", Generator = "increment", UnsavedValue = "0")]
public int Codigo
{
get { return codigo; }
set { codigo = value; }
}
[ManyToOne(0, Name = "Empresa", ClassType = typeof(Empresa), Column = "ID_EMPRESA", Lazy = Laziness.False)]
public Empresa Empresa
{
get { return empresa; }
set { empresa = value; }
}
[Property(Column = "VLR_FINANCIAMENTO", Lazy = false)]
public decimal VlrFinanciamento
{
get { return vlrFinanciamento; }
set { vlrFinanciamento = value; }
}
[Property(Column = "INSC_ESTADUAL", Lazy = false)]
public string InscEstadual
{
get { return inscEstadual; }
set { inscEstadual = value; }
}
[Property(Column = "ANO_MES_BASE", Lazy = false)]
public string AnoMesBase
{
get { return anoMesBase; }
set { anoMesBase = value; }
}
[Property(Column = "ANO_MES_FATURA", Lazy = false)]
public string AnoMesFaturamento
{
get { return anoMesFaturamento; }
set { anoMesFaturamento = value; }
}
[Property(Column = "VLR_ICMS_PREVISTO", Lazy = false)]
public decimal VlrICMSPrevisto
{
get { return vlrICMSPrevisto; }
set { vlrICMSPrevisto = value; }
}
[Property(Column = "TOTAL_RECOLHIDO", Lazy = false)]
public decimal TotalRecolhimento
{
get { return totalRecolhimento; }
set { totalRecolhimento = value; }
}
[Property(Column = "DATA_ULTIMO_RECOL", Lazy = false)]
public DateTime DatUltimoRecolhimento
{
get { return datUltimoRecolhimento; }
set { datUltimoRecolhimento = value; }
}
[Property(Column = "TOTAL_LIBERACAO", Lazy = false)]
public decimal VlrTotalLiberacao
{
get { return totalLiberacao; }
set { totalLiberacao = value; }
}
[Property(Column = "DAT_ULTIMA_LIBERACAO", Lazy = false)]
public DateTime DatUltimaLiberacao
{
get { return datUltimaLiberacao; }
set { datUltimaLiberacao = value; }
}
[Property(Column = "TOTAL_DEVOLUCAO", Lazy = false)]
public decimal TotalDevolucao
{
get { return totalDevolucao; }
set { totalDevolucao = value; }
}
[Property(Column = "DSC_OBSERVACAO", Lazy = false)]
public string DescObservacao
{
get { return descObservacao; }
set { descObservacao = value; }
}
[Property(Column = "DAT_LIBERACAO", Lazy = false)]
public DateTime DatLiberacao
{
get { return datLiberacao; }
set { datLiberacao = value; }
}
[Property(Column = "MES_BASE", Lazy = false)]
public int MesBase
{
get { return mesBase; }
set { mesBase = value; }
}
}
}
using Dominio.Domain;
using NHibernate;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Dominio.DataAccess
{
public class FinanciamentoDAO
{
public static List<Financiamento> ListarTodos()
{
try
{
ISession sessao = NhibernateHelper.SessaoCorrente;
Financiamento financiamento = new Financiamento();
ICriteria criterios = sessao.CreateCriteria(financiamento.GetType());
return criterios.List<Financiamento>().ToList();
}
catch (Exception e)
{
throw new Exception(e.ToString());
}
}
public static void InserirOuAtualizar(Financiamento financiamento)
{
ISession sessao = NhibernateHelper.SessaoCorrente;
ITransaction transacao = sessao.BeginTransaction();
try
{
sessao.SaveOrUpdate(financiamento);
transacao.Commit();
}
catch (Exception e)
{
transacao.Rollback();
throw new Exception(e.ToString());
}
}
public static void Deletar(Financiamento financiamento)
{
ISession sessao = NhibernateHelper.SessaoCorrente;
ITransaction transacao = sessao.BeginTransaction();
try
{
sessao.Delete(financiamento);
transacao.Commit();
}
catch (Exception e)
{
transacao.Rollback();
throw new Exception(e.ToString());
}
}
internal static Financiamento BuscarPorInscEstadual(string InscEstadual)
{
try
{
ISession sessao = NhibernateHelper.SessaoCorrente;
Financiamento financiamento = new Financiamento();
ICriteria criterios = sessao.CreateCriteria(financiamento.GetType());
criterios.Add(NHibernate.Criterion.Expression.Eq("InscEstadual", InscEstadual));
return criterios.UniqueResult() as Financiamento;
}
catch (Exception e)
{
throw new Exception(e.ToString());
}
}
internal static Financiamento BuscarPorIDFinanciamento(int COD_FINANCIAMENTO)
{
try
{
ISession sessao = NhibernateHelper.SessaoCorrente;
Financiamento financiamento = new Financiamento();
ICriteria criterios = sessao.CreateCriteria(financiamento.GetType());
criterios.Add(NHibernate.Criterion.Expression.Eq("Codigo", COD_FINANCIAMENTO));
return criterios.UniqueResult() as Financiamento;
}
catch (Exception e)
{
throw new Exception(e.ToString());
}
}
internal static List<Financiamento> ListarPorEmpresa(int ID_EMPRESA)
{
ISession sessao = NhibernateHelper.SessaoCorrente;
Financiamento financiamento;
try
{
financiamento = new Financiamento();
ICriteria criterios = sessao.CreateCriteria(financiamento.GetType());
criterios.CreateAlias("Empresa", "e").Add(NHibernate.Criterion.Expression.Eq("e.Codigo", ID_EMPRESA));
return criterios.List<Financiamento>().ToList();
}
catch (Exception e)
{
throw new Exception(e.ToString());
}
}
}
}
using Dominio.DataAccess;
using Dominio.Domain;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Dominio.APL
{
public class AplFinanciamento
{
public void gravar(Financiamento financiamento)
{
FinanciamentoDAO.InserirOuAtualizar(financiamento);
}
public void deletar(Financiamento financiamento)
{
FinanciamentoDAO.Deletar(financiamento);
}
public List<Financiamento> listarTodas()
{
return FinanciamentoDAO.ListarTodos();
}
public Financiamento buscarPorInscEstadual(string InscEstadual)
{
return FinanciamentoDAO.BuscarPorInscEstadual(InscEstadual);
}
public Financiamento buscarPorIDFinanciamento(int IDFinanciamento)
{
return FinanciamentoDAO.BuscarPorIDFinanciamento(IDFinanciamento);
}
public List<Financiamento> listarFinanciamentoPorEmpresa(int idEmpresa)
{
return FinanciamentoDAO.ListarPorEmpresa(idEmpresa);
}
}
}
Esse é meu .cs porém não estou conseguindo fazer funcionar, porque me retorna tudo null ao compilar o código e desconfio que a minha lógica esteja errada.
using Dominio.APL;
using Dominio.Domain;
using dap.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
namespace dapView.Relatorios.RelFinancLiberadoMesBase
{
public partial class RelFinancLiberadoMesBase : System.Web.UI.Page
{
private AplFinanciamento aplFinanciamento = new AplFinanciamento();
private List<Financiamento> financiamento = new List<Financiamento>();
private static bool keyJS { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
keyJS = true;
// CarregarComboLiberado();
if (!IsPostBack)
{
GerenciadorUsuarioPagina.funcao = "RELFIN01";
//btnImprime.Visible = false;
}
}
//Carrega os dados relacionando o tipo de liberação por data
//private void CarregarComboLiberado()
// {
// ddlLiberado.Items.Add("---------Selecione----------");
// ddlLiberado.Items.Add("Mês Base");
// ddlLiberado.Items.Add("Período");
// }
protected void btnConsultar_Click(object sender, EventArgs e)
{
CarregaRelatorio();
}
protected void ddlLiberado_SelectedIndexChanged(object sender, EventArgs e)
{
}
public void CarregaRelatorio()
{
financiamento = aplFinanciamento.listarTodas();
var dados = (from financiamento in financiamento
where DateTime.Compare(financiamento.DatUltimaLiberacao, Convert.ToDateTime(txtMesBase.Text.ToString())) == 0
group financiamento by new { financiamento.Codigo, financiamento.Empresa.InscEstadual, financiamento.Empresa.RazaoSocial, financiamento.Empresa.Cnpj, financiamento.Empresa.NomeAbreviado, financiamento.AnoMesBase } into g
select new
{
codigo = g.Key.Codigo,
AnoMesBase = g.Key.AnoMesBase,
InscricaoEstadual = g.Key.InscEstadual,
RazaoSocial = g.Key.RazaoSocial,
Cnpj = g.Key.Cnpj,
NmeAbreviado = g.Key.NomeAbreviado
}).OrderBy(o => o.codigo).ToList();
if (dados.Count() > 0)
{
//Carrega os dados da gridview de consulta
gv.DataSource = dados;
gv.DataBind();
gv.UseAccessibleHeader = true;
gv.HeaderRow.TableSection = TableRowSection.TableHeader;
//Carrega os dados da gridview usada para imprimir
gvImprimir.DataSource = dados;
gvImprimir.DataBind();
gvImprimir.UseAccessibleHeader = true;
gvImprimir.HeaderRow.TableSection = TableRowSection.TableHeader;
//mostra botão imprimir
//btnImprime.Visible = true;
}
else
{
if (keyJS) chamarSwal("aviso", "Não foram encontrados financiamentos para essa data.");
// btnImprime.Visible = false;
}
}
private void chamarSwal(string tipo, string mensagem)
{
var body = (HtmlGenericControl)(Page.Master.FindControl("body"));
body.Attributes["onload"] = $"{tipo}(\"{mensagem}\")";
keyJS = false;
}
}
}
Esse é o meu html
<%@ Page Title="" Language="C#" MasterPageFile="~/Content/MasterPage.Master" AutoEventWireup="true"
CodeBehind="RelFinanciamento.aspx.cs" Inherits="dapView.Relatorios.RelFinancLiberadoMesBase.RelFinancLiberadoMesBase" %>
<asp:Content ID="head" ContentPlaceHolderID="headPlaceHolder" runat="server">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css">
<script src="../JsRelatorioFinancLiberadoMesBase.js"></script>
<script>
var d = "16/09/2019" // date received from card
function filldate() {
document.getElementById('cardexpirydate').value = d.split('/').reverse().join("-");
}
</script>
<script>
function exibir_ocultar(val) {
if (val.value == 'LiberadoMesBase') {
document.getElementById('periodo').style.display = 'none';
document.getElementById('MesBase').style.display = 'block';
document.getElementById('periodo').style.display = 'none';
}
else {
document.getElementById('periodo').style.display = 'block';
document.getElementById('MesBase').style.display = 'none';
}
};
</script>
</asp:Content>
<asp:Content ID="ContentForm" ContentPlaceHolderID="formPlaceHolder" runat="server">
<asp:ScriptManager runat="server"></asp:ScriptManager>
<div class="row">
<div class="col-md-12">
<div class="content-box">
<div class="box-title">Financiamento</div>
<div class="box-body">
<div id="triage">
<label for="category">Liberado:</label>
<div class="form-inline">
<div class="col-md-2">
<label class="radio-inline control-label">
<input checked="checked" name="TaskLog.TaskTypeId" type="radio" value="2">
SIM
</label>
<label class="radio-inline control-label">
<input id="TaskLog_TaskTypeId" name="TaskLog.TaskTypeId" type="radio" value="1">
NÃO
</label>
</div>
<div id="category-select">
<select onchange="exibir_ocultar(this)" class="col-md-3 form-control" id="category" name="category" style="width: auto">
<option value="LiberadoMesBase">-----------Selecione----------</option>
<option value="LiberadoMesBase">Mês Base</option>
<option value="LiberadoPeriodo">Período</option>
</select>
</div>
</div>
<br />
<div class="row">
<div class="form-group">
<label class="radio-inline control-label">
<input type="radio" name="optradio" checked>Sim</label>
<label class="radio-inline">
<input type="radio" name="optradio">Não</label>
</div>
<br />
<div id="periodo">
<asp:TextBox type="Month" Style="width: 10%" runat="server" ClientIDMode="Static" class="form-control " ID="TextBox1" MaxLength="30"></asp:TextBox>
<br />
</div>
<br />
<div id="MesBase">
<asp:TextBox type="date" Style="width: 10%" runat="server" ClientIDMode="Static" class="form-control " ID="TextBox2" MaxLength="30"></asp:TextBox>
<br />
</div>
</div>
</div>
<div class="row">
<div class="content-box content-box-tabela" id="tabela" style="visibility: hidden">
<asp:GridView class="col-md-12" CssClass="tabela-padrao tabela-padrao-borda dataTable" runat="server" AutoGenerateColumns="False" PageSize="9" ID="gv" Width="100%">
<Columns>
<asp:TemplateField HeaderText="Empresa" ItemStyle-HorizontalAlign="Left">
<ItemTemplate>
<asp:Label ID="lblCodigo" runat="server" Text='<%# Bind("Codigo") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Valor Financiamento" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label ID="lblValorFinanciamento" runat="server" Text='<%# Bind("ValorFinanciamento") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Inscricao Estadual" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label ID="lblInscricaoEstadual" runat="server" Text='<%# Bind("InscricaoEstadual") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Ano mes base" ItemStyle-HorizontalAlign="Right">
<ItemTemplate>
<asp:Label ID="lblAnoMesBase" runat="server" Text='<%# Bind("AnoMesBase") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<PagerStyle CssClass="" HorizontalAlign="Center" />
</asp:GridView>
</div>
</div>
</div>
<div class="box-footer">
<button runat="server" class="btn btn-padrao" id="btnConsultar" onserverclick="btnConsultar_Click">Consultar</button>
</div>
</div>
<%--IMPRIMIR--%>
<div class="container" style="visibility: hidden" id="ConteinerImprimir">
<div class="table" runat="server" style="margin: 0 auto; width: auto;">
<div class="row">
<div class="col-lg-12">
<img src="http://internet.sefaz.es.gov.br/imagens/topo_brasao.png" alt="">
<br>
<br>
</div>
</div>
<div class="row" runat="server" style="border-bottom: 2px solid #B0BEC5">
<div class="col-lg-5">
<strong>Financiamento</strong>
</div>
<div class="col-lg-5" style="text-align: end;" runat="server" id="totalRegistros"></div>
</div>
</div>
<div class="row">
<div class="content-box content-box-tabela">
<asp:GridView class="col-md-12 grid" runat="server" AutoGenerateColumns="False" PageSize="9" ID="gvImprimir" GridLines="None"
RowStyle-HorizontalAlign="Center" Width="100%">
<Columns>
<asp:TemplateField HeaderText="Empresa" ItemStyle-HorizontalAlign="Left">
<ItemTemplate>
<asp:Label ID="lblCodigo" runat="server" Text='<%# Bind("Codigo") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Valor Financiamento" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label ID="lblValorFinanciamento" runat="server" Text='<%# Bind("ValorFinanciamento") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Inscricao Estadual" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label ID="lblInscricaoEstadual" runat="server" Text='<%# Bind("InscricaoEstadual") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Ano mes base" ItemStyle-HorizontalAlign="Right">
<ItemTemplate>
<asp:Label ID="lblAnoMesBase" runat="server" Text='<%# Bind("AnoMesBase") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<PagerStyle CssClass="" HorizontalAlign="Center" />
</asp:GridView>
</div>
</div>
</div>
</div>
</div>
</asp:Content>
Se alguém puder me ajudar, agradeço.Discussão (0)
Carregando comentários...