ReportView without DataSet

0

I am finishing my TCC and I have a question regarding Reports with ReportView of Visual Studio 2013. I'll basically explain with 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>

This ConnectionString is dynamic, that is, the application can connect to the database with different users and different database servers. The editing of ConnectionString is done by the code below, receiving the ones of the Logon 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 you have how to mount the Report using this connection with SQL, that is, without mounting a DataSet. Or is there any way to load the contents of a DataGridView in the ReportView and thus mount the Report?

    
asked by anonymous 08.10.2014 / 15:49

2 answers

1

Firstly if you are working with the crystal report, I recommend that you see some tutorial, because it is a bit complicated to use.

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

Firstly I recommend that you use datasets ... I've had many issues with objects ...

Home screen ...

privatevoidbtnImprimir_Click(objectsender,EventArgse){try{List<object>ListParams=newList<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

On this screen you should 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 the reports by type ... I have 1 dataset inside it and the report screen itself.

Report

Now, just add the dataset in the report and that's it!

If you have problems related to the look 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 questions leave a comment ...

    
09.10.2014 / 20:26
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 with only the fields (properties) of your table.

In the form that calls rdlc, you do the binding through a list.

Example:

SaleLordIDMLLBindingSource.DataSource = LostListlist;

Notice that I'm passing a list to the DataSource. This list is of the same type as the one you created there in the rdlc dataset.

If you need it, I will further detail my explanation

    
08.10.2014 / 21:41