Reportview without a dataset

Asked

Viewed 2,459 times

0

I am finishing my TCC and I have a question regarding the Reports with the ReportView from Visual Studio 2013. I will explain basically how my application works.

The connection to the database is made through a ConnectionString declared in the application configuration file. Ex.:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
    <add key="conexao" value="Data Source=localhost;Initial Catalog=BD;User ID=admin;Password=admin" />
</appSettings>
<startup> 
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>

That one ConnectionString is dynamic, that is, the application can connect to the database with different users and different Database servers. The ConnectionString is made by the code below receiving those from the Login Form that are passed the variables "server, user and password":

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings.Remove("conexao");
config.AppSettings.Settings.Add("conexao", "Data Source=" + server + ";Initial Catalog=BD;User ID=" + user + ";Password=" + senha);
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");

And Sqlconnection is declared as below:

SqlConnection cx=new SqlConnection(ConfigurationManager.AppSettings["conexao"]);

The problem is that I do not know if there is a way to assemble the Report using this connection with SQL, that is, without mounting a Dataset. Or if there is any way to load the contents of a Datagridview in Reportview and so assemble the Report?

2 answers

1

First, if you are working with Crystal report, I recommend that you see some tutorial, because it is a little complicated to use.

I will give you an example that I use and can be very useful for your learning...

First, I recommend that you use datasets... I’ve had a lot of problems with objects...

Home screen...

tela1

private void btnImprimir_Click(object sender, EventArgs e)
    {
        try
        {
            List<object> ListParams = new List<object>();

            ListParams.Add(dtpPeriodoInicio.Value.ToString("yyyy-MM-dd"));
            ListParams.Add(dtpPeriodoFinal.Value.ToString("yyyy-MM-dd"));
            ListParams.Add(Convert.ToInt32(String.IsNullOrEmpty(ucTxtBtnFornecedor.TextComponent) ? "0" : ucTxtBtnFornecedor.TextComponent));
            ListParams.Add(Convert.ToInt32(String.IsNullOrEmpty(ucTxtBtnProduto.TextComponent) ? "0" : ucTxtBtnProduto.TextComponent));

            frmPreviewCompra frmPreviewAnalitica = new frmPreviewCompra("RelatorioConferenciaComprasAnalitica", ListParams);
            frmPreviewAnalitica.ShowDialog();
        }
        catch (Exception ex)
        {
            UIErrors.ShowErrors("Erro ao tentar realizar a impressão.\nErro: " + ex.Message, MessageBoxIcon.Error);
        }
    }

Preview Screen

In this screen Voce must have the component Crystaldecisions.Windows.Forms.Crystalreportviewer

public partial class frmPreviewCompra : Form
{
    #region Attributes
    string _tipoRelatorio;
    List<object> _param;
    #endregion Attributes

    #region Constructors
    public frmPreviewCompra()
    {
        InitializeComponent();
    }

    /// <summary>
    /// Construtor do form de visualização do relatório. É necessário passar a sequência
    /// correta de valores na variável Param, pois ela é um array de object na qual no load
    /// do form eu carrego esses valores do array para os parametros do relatório.
    /// 
    /// Obs: Caso for passado errado o relatório sairá errado as informações.
    /// </summary>
    /// <param name="TipoRelatorio">Define o tipo de relatório que será carregado</param>
    /// <param name="Param">Array com os parametros do relatório</param>
    public frmPreviewCompra(string TipoRelatorio, List<object> Param) : this()
    {
        this._tipoRelatorio = TipoRelatorio;
        this._param = Param;
    }
    #endregion Constructors

    #region Form Events
    private void frmPreviewCompra_Load(object sender, EventArgs e)
    {
        string where = String.Empty, fields = String.Empty, join = String.Empty, orderBy = String.Empty;

        switch (_tipoRelatorio)
        {
            case "RelatorioConferenciaComprasAnalitica":
                dsCompras dsRelCompras = new dsCompras();
                crRelatorioConferenciaComprasAnalitico crComprasAnalitico = new crRelatorioConferenciaComprasAnalitico();

                fields = @"empresa.RazaoLst,
                           concat(nf_entrada.IDParceiroFornec, ' - ', parceiro.Nome) Fornecedor,
                           nf_entrada.NumeroNota NroNotaEntrada,
                           nf_entrada.DataEmissao,
                           nf_entrada.DataEntrada,
                           nf_entrada_produto.IDProduto,
                           produto.Descricao DescricaoProduto,
                           nf_entrada_produto.QtdeProduto,
                           nf_entrada_produto.TotalLiquido,
                           (nf_entrada_produto.TotalLiquido / nf_entrada_produto.QtdeProduto) PrecoMedio";

                join = @"join parceiro on parceiro.ID = nf_entrada.IDParceiroFornec
                         join nf_entrada_produto on nf_entrada_produto.IDNFEntrada = nf_entrada.ID
                         join produto on produto.ID = nf_entrada_produto.IDProduto
                         join empresa on empresa.ID = nf_entrada.IDEmpresa";

                where = @"nf_entrada.DataEntrada between '" + _param[0] + "' and '" + _param[1] + "'" +
                        " AND (((" + Convert.ToInt32(_param[2]) + " > 0) AND (coalesce(nf_entrada.IDParceiroFornec, 0) = " + Convert.ToInt32(_param[2]) + ")) OR ((" + Convert.ToInt32(_param[2]) + " = 0) AND (coalesce(nf_entrada.IDParceiroFornec, 0) >= 0)))" +
                        " AND (((" + Convert.ToInt32(_param[3]) + " > 0) AND (coalesce(nf_entrada_produto.IDProduto, 0) = " + Convert.ToInt32(_param[3]) + ")) OR ((" + Convert.ToInt32(_param[3]) + " = 0) AND (coalesce(nf_entrada_produto.IDProduto, 0) >= 0)))";

                orderBy = "Fornecedor";

                dsRelCompras.Tables["dtRelatorioCompraAnalitica"].Merge(Metodos_NF_Entrada.GetAllNotaFiscalEntrada(fields, where, join, orderBy, "", true));

                crComprasAnalitico.SetDataSource(dsRelCompras.Tables["dtRelatorioCompraAnalitica"]);

                CrystalDecisions.Shared.ParameterField pComprasDataEntradaIni = new CrystalDecisions.Shared.ParameterField();
                CrystalDecisions.Shared.ParameterField pComprasDataEntradaFin = new CrystalDecisions.Shared.ParameterField();
                CrystalDecisions.Shared.ParameterField pComprasFornecedor = new CrystalDecisions.Shared.ParameterField();
                CrystalDecisions.Shared.ParameterField pComprasProduto = new CrystalDecisions.Shared.ParameterField();

                pComprasDataEntradaIni = crComprasAnalitico.ParameterFields["@DataIni"];
                pComprasDataEntradaFin = crComprasAnalitico.ParameterFields["@DataFin"];
                pComprasFornecedor = crComprasAnalitico.ParameterFields["@Fornecedor"];
                pComprasProduto = crComprasAnalitico.ParameterFields["@Produto"];

                pComprasDataEntradaIni.CurrentValues.AddValue(Convert.ToDateTime(_param[0]).ToString("dd/MM/yyyy"));
                pComprasDataEntradaFin.CurrentValues.AddValue(Convert.ToDateTime(_param[1]).ToString("dd/MM/yyyy"));
                pComprasFornecedor.CurrentValues.AddValue(_param[2].ToString());
                pComprasProduto.CurrentValues.AddValue(_param[3].ToString());

                crViewerCompras.ReportSource = crComprasAnalitico;
                break;

            case "RelatorioConferenciaComprasSintetica":

                break;
        }
    }
    #endregion Form Events
}

Data Sets

I use several projects to separate well the reporters by type... inside it I have 1 dataset and the screen of the report itself.

tela3 tela2

Report

Now just add the dataset in the report and ready!

tela4

If you have problems related to the visual of the report itself... it would be advisable to create another question and let us know by leaving a new comment here with the link.

Any doubt leave a comment...

  • I also asked a question that I have doubts about, follow the link: http://answall.com/questions/35519/fillr-dataset-com-datatable

  • Ariel... is exactly what I do in the example.

0

You can work with objects. You will need, there in the report (rdlc), to create the Dataset, however, at the moment of creation, you will indicate Object. For this, you need to have a class only with the fields (properties) of your table.

Done this, in the form that calls the rdlc, you make the Binding through a list.

Example:

Vendaperdidamlindingsource.Datasource = listVendaPerdida;

Note that I am passing a list to Datasource. This list is the same as the one you created there in the rdlc dataset.

If you need me, I’ll explain further

  • thanks for the reply. Could detail better?

  • In my case I perform the query to the database, and the method responsible for it returns me a Datatable. Can I specify this table as the Datasource for Report? Ex.: myRelatory.Datasource = table;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.