When I generate it on runtime, it doesn't show any data. But it does when I check on the 'Main Report Preview' of VS 2010. I have also checked my stored procedure, it does produce data when I execute it. What seems to be the problem?
This is my code in page_load:
protected void Page_Load(object sender, EventArgs e)
{
string municipio = Request.QueryString["municipio"];
string ano = Request.QueryString["ano"];
string cnpj = Server.UrlDecode(Request.QueryString["cnpj"]);
DataTable dt;
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection cnn = new SqlConnection(CS))
{
cnn.Open();
//stored procedure
SqlCommand cmd = new SqlCommand("spConsultaRelatorioCompleto", cnn);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#ano", ano);
cmd.Parameters.AddWithValue("#municipio", municipio);
cmd.Parameters.AddWithValue("#cnpj", cnpj);
//read access to the database
SqlDataReader dr = cmd.ExecuteReader();
SqlDataAdapter da = new SqlDataAdapter(cmd);
//datatable with data
dt = new DataTable("dt");
//datatable with datareader's data
dt.Load(dr);
da.Fill(dt);
}
ReportDocument MeuRelatorio = new ReportDocument();
MeuRelatorio.Load(Server.MapPath("RelatorioConvenio.rpt"));
MeuRelatorio.SetDataSource(dt);
CrystalReportViewer1.ReportSource = MeuRelatorio;
}
}
}
I give some values in another webform when I click the button below:
protected void btnExport_Click(object sender, EventArgs e)
{
Response.Redirect("RelatorioGerado.aspx?municipio=" + ddlmunicipioconvenente.Text + "&cnpj=" + Server.UrlEncode(tbcnpjconvenente.Text) + "&ano=" + tbAno.Text);
}
Related
Why crystal report prompting me for parameter field value while I have written code for it.
Private void ReportVeiwer_Load(object sender, EventArgs e)
{
ReportDocument reportdoc = new ReportDocument();
///string invoice_number = (;
Invoice invoicerpt = new Invoice();
ParameterField paramfield = new ParameterField();
ParameterFields paramfields = new ParameterFields();
paramfield.Name = "Invoice_Number";
ParameterDiscreteValue dicval = new ParameterDiscreteValue();
dicval.Value = User_Info.invoice_number;
paramfield.CurrentValues.Add(dicval);
paramfields.Add(paramfield);
ReportVeiwer rptveiwer = new ReportVeiwer();
rptveiwer.crystalReportViewer1.ParameterFieldInfo = paramfields;
reportdoc.Load(#"D:\Furqan\SchoolManagementSystem\SchoolManagementSystem\Invoice.rpt");
crystalReportViewer1.ReportSource = reportdoc;
reportdoc.SetDatabaseLogon("PC-Name/User", "Password", ".", "Database");
}
Load the report first. Then, set the parameter value...
private void dataGridView1_RowHeaderMouseClick_1(object sender, DataGridViewCellMouseEventArgs e)
{
int ID = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString());
txtName.Text = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
txtFname.Text = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();
txtAddress.Text = dataGridView1.Rows[e.RowIndex].Cells[3].Value.ToString();
}
private void btnEdit_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("Update student set name ='"+txtName.Text+"', fathername= '"+txtFname.Text+"', address= '"+txtAddress.Text+"' where id = ID", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Display();
MessageBox.Show("Record is Updated");
When i run this code then my whole database table is updated with the current values and i can't understand the problem
"where id = ID" condition is always true so all records are affected. You need to actually set a value for "ID". Perhaps you need to write
"where id =" + ID.ToString()
I have many rpt files. I want to change the query for each report using C#. There are several ways to do this changes.
First way:
private void button_Test_Click(object sender, EventArgs e)
{
ReportDocument rptDoc = new ReportDocument();
rptDoc.Load("D:\\Temp_01\\Report1_Test.rpt");
rptDoc.SetDatabaseLogon("User", "Password", "ServName", "DBName");
CrystalDecisions.Shared.ConnectionInfo ConnInf;
ConnInf = rptDoc.Database.Tables[0].LogOnInfo.ConnectionInfo;
String strSQLQuery = "SELECT TOP(123) * FROM sys.all_objects";
String strTableName = rptDoc.Database.Tables[0].Name;
try
{
rptDoc.SetSQLCommandTable(ConnInf, strTableName, strSQLQuery);
rptDoc.VerifyDatabase();
}
catch (Exception ex) { rptDoc.Close(); }
rptDoc.SaveAs("D:\\Temp_02\\Report2_Test.rpt");
rptDoc.Close();
}
It is not the best way. The method SetSQLCommand does not work when the query has any parameters. Even if you set value for each parameter, SetSQLCommand does not work. The example with a parameter which does not work:
private void button_Test_Click(object sender, EventArgs e)
{
ReportDocument rptDoc = new ReportDocument();
rptDoc.Load("D:\\Temp_01\\Report1_Test.rpt");
rptDoc.SetDatabaseLogon("User", "Password", "ServName", "DBName");
CrystalDecisions.Shared.ConnectionInfo ConnInf;
ConnInf = rptDoc.Database.Tables[0].LogOnInfo.ConnectionInfo;
String strSQLQuery = "SELECT TOP(1) * FROM sys.all_objects WHERE name = {?strName}";
String strTableName = rptDoc.Database.Tables[0].Name;
try
{
rptDoc.SetParameterValue("strName", "Text");
rptDoc.SetSQLCommandTable(ConnInf, strTableName, strSQLQuery);
rptDoc.VerifyDatabase();
}
catch (Exception ex) { rptDoc.Close(); }
rptDoc.SaveAs("D:\\Temp_02\\Report2_Test.rpt");
rptDoc.Close();
}
It returns an error. This method does not work with parameters!
Second way:
private void button_Test_Click(object sender, EventArgs e)
{
ReportDocument rptDoc = new ReportDocument();
rptDoc.Load("D:\\Temp_01\\Report1_Test.rpt");
rptDoc.SetDatabaseLogon("User", "Password", "ServName", "DBName");
ISCDReportClientDocument rcd = null;
rcd = rptDoc.ReportClientDocument as ISCDReportClientDocument;
CommandTable rTblOld;
CommandTable rTblNew;
rTblOld = rcd.Database.Tables[0] as CommandTable;
rTblNew = rcd.Database.Tables[0].Clone(true) as CommandTable;
rTblNew.CommandText = "SELECT TOP(1) * FROM sys.all_objects";
try
{
rcd.DatabaseController.SetTableLocationEx(rTblOld, rTblNew);
rcd.VerifyDatabase();
}
catch (Exception ex) { rcd.Close(); }
rcd.SaveAs(rcd.DisplayName, "D:\\Temp_02\\", 1);
rcd.Close();
}
This is also not the best way. The method SetLocalTableEx does a struct of the report is bad. After run SetLocalTableEx, attribute ConnectionInf.UserId have value NULL also the Name of connection
After SetTableLocationEx:
rcd.DatabaseController.SetTableLocationEx(rTblOld, rTblNew);
String UserID;
UserID = rptDoc.Database.Tables[0].LogOnInfo.ConnectionInfo.UserID;
if (UserID == null) MessageBox.Show("UserID has NULL");
UserId has value NULL
Also, before run SetTableLocationEx, Connection Name is MSODBCSQL11
enter image description here
After run SetTableLocationEx, Connection Name is Command
enter image description here
So,
how do dynamic and correctly to change the query in CommandTable for Crystal Reports file?
Thanks,
Artem
You are using command in Crystal Report which is the best way when doing and displaying a data from database to crystal report but unfortunately you do it in Code Behind.
My Question is:
Why don't you do it in Command of Crystal Report itself?
see this link for more info.
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.Security;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls.WebParts;
using System.Drawing.Imaging;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Xml;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.ReportSource;
using CrystalDecisions.Reporting;
using CrystalDecisions.Shared;
using CrystalDecisions.Web;
public partial class Schools : System.Web.UI.Page
{
ReportDocument crystalReport = new ReportDocument();
protected void Page_Init(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
try
{
string query = "select * from School Where Designation = 'Public' Order by School ASC";
crystalReport.Load(Server.MapPath("ReportPrimary.rpt"));
MPrimary dsCustomers = GetData(query);
crystalReport.SetDataSource(dsCustomers);
crystalReport.SetDatabaseLogon("username", "password.34", "mssql.webaddress.net,4118", "dataDB");
SchReport.ReportSource = crystalReport;
Session["ReportDocument"] = crystalReport;
}
catch (LogOnException ex)
{
//Throws an exception if an error is encountered on retrieval
}
}
else
{
string query = "select * from School Where Designation = " + "'" + drpSchoolDesignation.SelectedValue + "'" + " Order by School ASC";
// ReportDocument crystalReport = new ReportDocument();
crystalReport.Load(Server.MapPath("ReportPrimary.rpt"));
TextObject to = (TextObject)crystalReport.ReportDefinition.Sections["Section2"].ReportObjects["Text3"];
to.Text = drpSchoolDesignation.SelectedValue.ToUpper() + " SCHOOLS";
MPrimary dsCustomers = GetData(query);
crystalReport.SetDataSource(dsCustomers);
SchReport.FindControl("Text3");
crystalReport.SetDatabaseLogon("username", "password.34", "mssql.webaddress.net,4118", "dataDB");
ReportDocument doc = (ReportDocument)Session["ReportDocument"];
SchReport.ReportSource = doc;
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
private void OpenNewWindow(string url, string windowName, string windowParams)
{
if (url == null)
throw new ArgumentNullException("url");
if (windowName == null)
windowName = "";
if (windowParams == null)
windowParams = "";
string scriptCode =
string.Format(
"<script>window.open('{0}','{1}','{2}');</script>",
url, windowName, windowParams);
//write the script out to HTTP Response stream
Response.Write(scriptCode);
}
private MPrimary GetData(string query)
{
string conString = ConfigurationManager.ConnectionStrings["DBConnectionString1"].ConnectionString;
SqlCommand cmd = new SqlCommand(query);
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (MPrimary dsCustomers = new MPrimary())
{
sda.Fill(dsCustomers, "School");
return dsCustomers;
}
}
}
}
protected void drpSchoolDesignation_SelectedIndexChanged(object sender, EventArgs e)
{
drpDisplay.SelectedIndex = 0;
drpSort.SelectedIndex = 0;
string query = "select * from School Where Designation = " + "'" + drpSchoolDesignation.SelectedValue + "'" + " Order by School ASC";
crystalReport.Load(Server.MapPath("ReportPrimary.rpt"));
TextObject to = (TextObject)crystalReport.ReportDefinition.Sections["Section2"].ReportObjects["Text3"];
to.Text = drpSchoolDesignation.SelectedValue.ToUpper() + " SCHOOLS";
MPrimary dsCustomers = GetData(query);
crystalReport.SetDataSource(dsCustomers);
crystalReport.SetDatabaseLogon("username", "password.34", "mssql.webaddress.net,4118", "dataDB");
Session["ReportDocument"] = crystalReport;
SchReport.ReportSource = crystalReport;
}
protected void CrystalReportViewer1_Unload(object sender, EventArgs e)
{
crystalReport.Close();
crystalReport.Dispose();
}
protected void Button1_Click(object sender, EventArgs e)
{
//Select data from DB
//Action to be added later
}
}
This code is supposed to retrieve and display info using crystal reports.
It seems my object is not been properly disposed. Modifying this code disables the user from ever getting to page 3 of the document. Any help would be appreciated. Thanks guys in advance.
Here is my code; loaddata method extracts data from student table and it returns datatable named "tbl_std". from button click I want to load data into datagridview and code is below. It only displays number of blank rows that are in the database table but not data. Help me as soon as possible......
private DataTable loaddata()
{
sqlcon.Open();
SqlDataAdapter sda = new SqlDataAdapter("select * from student",sqlcon);
DataSet ds = new DataSet();
sqlcon.Close();
sda.Fill(ds, "tbl_std");
return ds.Tables["tbl_std"];
}
private void button4_Click(object sender, EventArgs e)
{
dataGridView1.DataSource = loaddata();
}