Passing a Parameter - ReportViewer local mode - c#

Am tyring to pass a parameter in a local report using a ReportViewer control in VS2010. The user clicks on a merchant, and there is a button press (not shown) which then renders the report.
I've tried using this video : How-to Pass Parameter to Report Viewer - YouTube
Problem: Code doesn't work - near xxxx at the bottom I can't figure out what should be in there
Problem: I would love to get rid of this code and use linqtosql or something simpler.
protected void Page_Load(object sender, EventArgs e)
{
DataSet1TableAdapters.MerchantNamesTableAdapter merchantNamesTableAdapter = new DataSet1TableAdapters.MerchantNamesTableAdapter();
ddlMerchants.DataSource = merchantNamesTableAdapter.GetDataAllMerchants();
ddlMerchants.DataTextField = "Name";
ddlMerchants.DataValueField = "MerchantUID";
ddlMerchants.DataBind();
ReportViewer1.Visible = false;
}
protected void Button1_Click(object sender, EventArgs e)
{
ReportViewer1.Visible = true;
var newDataSet = new DataSet();
SqlConnection sqlConnection = new SqlConnection("Data Source=.;Initial Catalog=myDataBase;Integrated Security=True");
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter();
SqlCommand sqlCommand = new SqlCommand();
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandType = CommandType.Text;
sqlCommand.CommandText = "select * from merchant where merchantUID = #MerchantUID";
sqlCommand.Parameters.AddWithValue("#MerchantUID", ddlMerchants.SelectedValue);
sqlDataAdapter.SelectCommand = sqlCommand;
sqlDataAdapter.Fill(newDataSet);
ReportDataSource datasource = new ReportDataSource(xxxx, newDataSet.Tables(0));
ReportViewer1.LocalReport.DataSources.Clear();
ReportViewer1.LocalReport.DataSources.Add(datasource);
ReportViewer1.LocalReport.Refresh();
}

In scenario like this I usually follow this path:
I create a dataset for the report: select the report and the menu command View - Report Data; in the Report Data windows select New ... - Dataset. I enter a name for the dataset (suppose Redemptions) and I select New ... next by DataSource, then I select Object and I navigate to my domain (or dto) class. That done I see the fields of my class and I can use it in the report;
If needed I create parameters in the Report Data Windows (right click on the Parameters Node) and define the name and type of the parameter;
I write this code to pass the data and parameters (if needed) to the report:
viewer.Reset();
ReportDataSource dataSource = new ReportDataSource();
// I use a service/repository; you could also use Linq2Sql or EntityFramework
IList<Redemption> redemptions = _service.GetRedemptions(merchantId);
BindingSource bindingSource = new BindingSource(redemptions, string.Empty);
dataSource.Name = "Redemptions";
dataSource.Value = bindingSource;
viewer.LocalReport.DataSources.Add(getDataSource(sourceInfo));
String reportName = "AD.Conso.MyReport.rdlc";
viewer.LocalReport.ReportEmbeddedResource = reportName;
IList<ReportParameter> parameters = new List<ReportParameter>();
parameters.Add(new ReportParameter("myParameterName", "myParameterValue"));
viewer.LocalReport.SetParameters(parameters);
viewer.RefreshReport();
Note: I took this code from a project where I am using it in a slight different context, so some code could be not necessary in your context.

That xxxx is simply the name of the Datasource that you want to have. it can be anything and is used to by the constructor to Construct a named data source. Its simply an identifier . Like pass "Merchent_Redemptions" or whatever u like.

The datatable is being used as a constructor rather it should be written as an index..
Below is the code present
ReportDataSource datasource = new ReportDataSource(xxxx, newDataSet.Tables(0));
The code should be in this format
ReportDataSource datasource = new ReportDataSource(xxxx, newDataSet.Tables[0]);

If u have dataAdapator, DataSet then try this on form load:-
this.DataTableAdapter.Fill(this.myDatabase_DataSet.tableName, parameter01, parameter02);
this.reportViewer1.RefreshReport();

Related

How can I redirect to Report Viewer?

I am facing a problem while working with Reports in WPF... I have created an event
private void Window_Loaded(object sender, RoutedEventArgs e) {
try {
admissionReportViewer.Owner = Window.GetWindow(this);
if (_admissionNumber != 0) {
rd.Load(#"C:\\Users\Sohaib Khalid\source\repos\SMS Degree College\Reports\AdmissionForm - Copy.rpt");
SqlConnection conn = new SqlConnection();
conn.ConnectionString = ConfigurationManager.ConnectionStrings["Other"].ConnectionString;
conn.Open();
SqlDataAdapter sda = new SqlDataAdapter("SearchStudentInfoAllById", conn);
sda.SelectCommand.CommandType = System.Data.CommandType.StoredProcedure;
sda.SelectCommand.Parameters.AddWithValue("#AdmissionNumber", _admissionNumber);
sda.SelectCommand.Parameters.AddWithValue("#Active", _active);
DataSet ds = new DataSet();
sda.Fill(ds, "StudentTable");
rd.SetDataSource(ds);
admissionReportViewer.ViewerCore.ReportSource = rd;
}
}
catch(Exception err) {
this.ShowMessageAsync("No data", err.ToString());
Debug.WriteLine(err.ToString());
}
after this report also load but it again, ask for parameters:
and also credentials of server login
Can Anybody tell me why it is again asking for parameters?
Thanks
I never used ReportViewer in WPF app, but used it a couple of time on ASP.NET
If WPF works in the same way, you're code is wrong:
The report is using the data source you set up for design it and not the one you're passing to it
You're storing the parameter value in the data adapter (query) and not in the report parameters
This is why your report ask for both.
I'll share a bit of code for ASP, try to check if it can be the same for WPF or if you have to change it:
// Local mode says to use the datasource we are giving to the report
// instead of the one we used to design it
reportViewer.ProcessingMode = ProcessingMode.Local;
// Set the path of the report file
LocalReport localReport = reportViewer.LocalReport;
localReport.ReportPath = "PATH_OF_YOUR_REPORT";
// Extract data from the DB (remember to insert the parameters in the query)
var dataset = GetDataSet();
// Assign the dataset to the report source (we need a ReportDataSource)
var source = new ReportDataSource();
source.Name = "SOURCE_NAME_USED_IN_THE_REPORT";
source.Value = dataset.Tables["YOUR_TABLE"];
// Add the source to the report
localReport.DataSources.Add(source);
// Create your report parameter (ex: fromDate)
var paramFromDate = new ReportParameter();
paramDataDa.Name = "fromDate";
paramDataDa.Values.Add(paramFromDate.ToShortDateString());
// Set the report parameters for the report
localReport.SetParameters(new ReportParameter[] { fromDate });
I hope this can help you but remember, it is for ASP and not for WPF.
So try to adapt it to WPF and see if they work in the same way

A data source instance has not been supplied for the data source 'DataSet2'-SSRS

This is my First report using SSRS.
I am trying to generate a Report using SSRS in asp.net.
My Need is:
I want to create a report with multiple tables (4 tables) that have relationship with one another. I have configured each individual table with accepting 1 parameter, for instance:
What I tried is:
I have created a dataset.xsd with 4 tables and given the relationship between those tables.
Then I created a report.rdlc and designed a report with four tables and drag and dropped the required field to the table and created a report parameter called ID.
The error i'm Getting is:
A data source instance has not been supplied for the data source 'DataSet2'
What I have written in cs page on button click is:
protected void BtnGo_Click(object sender, EventArgs e)
{
DataSet2TableAdapters.TB_TransReceiptTableAdapter ta = new DataSet2TableAdapters.TB_TransReceiptTableAdapter();
DataSet2.TB_TransReceiptDataTable dt = new DataSet2.TB_TransReceiptDataTable();
ta.Fill(dt,Convert.ToInt16( TxtID.Text));
//ta.Fill(dt,TxtID.Text);
ReportDataSource rds = new ReportDataSource();
rds.Name = "DataSet2";
rds.Value = dt;
ReportParameter rp = new ReportParameter("ID", TxtID.Text.ToString());
rptviewer.LocalReport.DataSources.Clear();
rptviewer.LocalReport.ReportPath = "Report1.rdlc";
rptviewer.LocalReport.SetParameters(new ReportParameter[] { rp });
rptviewer.LocalReport.DataSources.Add(rds);
rptviewer.LocalReport.Refresh();
rptviewer.Visible = true;
}
The help i seek is:
I dont know how to bind the report via code, since I have four tables that are related to one another with foreign key. Above is the code I used but it throws an error.
I would be very thankful if some one could help me to solve this issue.
Thanks in advance.
As per tgolisch instead of table i Bound dataset and passed to report it works fine.
And also instead of four separate table i created a view .It Makes my job simple
private DataTable getData()
{
DataSet dss = new DataSet();
string sql = "";
sql = "SELECT * from VW_TransReciptReport WHERE tREC_NUPKId='" + TxtID.Text + "'";
SqlDataAdapter da = new SqlDataAdapter(sql, con);
da.Fill(dss);
DataTable dt = dss.Tables[0];
return dt;
}
private void runRptViewer()
{
this.rptviewer.Reset();
ReportParameter rp = new ReportParameter("ID", TxtID.Text.ToString());
this.rptviewer.LocalReport.ReportPath = Server.MapPath("ReportReceipt.rdlc");
rptviewer.LocalReport.SetParameters(new ReportParameter[] { rp });
ReportDataSource rdsB = new ReportDataSource("DataSet1_VW_TransReciptReport", getData());
this.rptviewer.LocalReport.DataSources.Clear();
this.rptviewer.LocalReport.DataSources.Add(rdsB);
this.rptviewer.DataBind();
this.rptviewer.LocalReport.Refresh();
}

report viewer in windows form not updating even after refresh report

i am try to generate report via report viewer using click event on button. its working fine. but when i update my data in database report viewer show only old report . i have tried using refresh report too.its not working. i am using table adapter in dataset to populate my data.
this.reportViewer1.Reset();
Microsoft.Reporting.WinForms.ReportDataSource reportDataSource2 = new Microsoft.Reporting.WinForms.ReportDataSource();
reportDataSource2.Name = "LedgerBy_partyID";
reportDataSource2.Value = this.Ledger_by_Party_IDBindingSource;
// this.ReportDataset.Ledger_by_Party_ID.Reset();
this.Ledger_by_Party_IDTableAdapter.Fill(this.ReportDataset.Ledger_by_Party_ID, selected_PartyID);
this.reportViewer1.LocalReport.ReportEmbeddedResource = "proj.userReport.Ledger_ByPartyID.rdlc";
this.reportViewer1.LocalReport.DataSources.Clear();
this.reportViewer1.LocalReport.DataSources.Add(reportDataSource2);
this.reportViewer1.LocalReport.Refresh();
this.reportViewer1.RefreshReport();
I just solved the same problem. I was searching for a few days in internet but I couldn't find a good answer for it. So I hope my post will help somebody to overcome the same problem.
All you need to do - just define manually the connection, refill the dataset and bind the source to reportviewer. Here is my project example:
using Microsoft.Reporting.WinForms;
private void ReportForm_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=D:\GD Robotics\VisualProjects\GDPolin\GDPolin\PolinaDB.mdf;Integrated Security=True;Connect Timeout=30";
conn.Open();
SqlDataAdapter reportDBTableAdapter = new SqlDataAdapter("SELECT * FROM [ReportDB]", conn);
DataTable polinaDBDataSet = new DataTable();
reportDBTableAdapter.Fill(polinaDBDataSet);
conn.Close();
this.reportViewer1.Reset();
this.reportViewer1.LocalReport.DataSources.Clear();
this.reportViewer1.LocalReport.ReportPath = #"D:\GD Robotics\VisualProjects\GDPolin\GDPolin\Report1.rdlc";
ReportDataSource rds = new ReportDataSource("DataSet1", polinaDBDataSet);//"DataSet1" is the name of your dataset. Go to .rdlc form>VIEW>Report Data>"Right click on dataset">Dataset Properties
this.reportViewer1.LocalReport.DataSources.Add(rds);
this.reportViewer1.RefreshReport();
}

adding crystal report via code

i successfully designed and filled my Crystal report via code not via wizard.
i added Crystal report via addNEWITEM
i added dataset in aap_code via addNEWITEM
i added datatable into dataset via addNEWITEM
Via code i made report and filled dataset and table with data
Run and display. Successfully done.
but my question is that how to do it fully via code like for steps 1,2,3 ? I don't want to add it via AddNewItem etc, isn't there any way to add these via code ? i did, i created some datasets and table via code like we do for Gridview etc but that doesn't appear in DATA connections of crystal report etc.
String conStr =WebConfigurationManager.ConnectionStrings["LoginDatabaseConnectionString"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Dataset_load();
}
}
protected void Dataset_load()
{
SqlConnection sqlcon = new SqlConnection(conStr);
SqlCommand sqlCom = new SqlCommand("select * from Login", sqlcon);
SqlDataAdapter sqlDA = new SqlDataAdapter(sqlCom);
// DataSet ds = new DataSet("CRDataSet");
try
{
sqlcon.Open();
//sqlCom.ExecuteNonQuery();
//sqlDA.Fill(ds,"Login");
DataSet1 ds = new DataSet1();
DataTable dt = new DataTable("DT_CR");
sqlDA.Fill(dt);
ds.Tables[0].Merge(dt);
ReportDocument rd = new ReportDocument();
rd.Load(Server.MapPath("CrystalReport.rpt"));
rd.SetDataSource(ds);
CrystalReportViewer1.ReportSource = rd;
}
catch (Exception exc)
{
Response.Write(exc.Message);
}
finally
{
sqlcon.Close();
}
I'm not sure why you would make it harder on yourself by trying to create all the code from scratch rather than using the functionality of VS. If you really want to do it though, I would create everything using the built-in functionality. Then I would look at all the code that gets added and see what does what.
There are some tutorials out there that tell you how to do it using the features. Create one and then read through the code.
That's how I would do it.
Hope that helps,
Chris

Binding textboxes to database (C# web developer)

I am using Microsoft Visual Web Developer 2010 Express. I have been trying to enter my textbox input into a database table I created. I ran into a problem using the DataBinding property (located under the BindTextBoxes method at the bottom). I searched the internet and found out that the DataBinding property does not exist in Web Developer. Is there an alternate way to transfer the textbox input into a database table?
Here is database part of my code (in C#):
namespace WebApplication2
{
public partial class _Default : System.Web.UI.Page
{
//used to link textboxes with database
BindingSource bsUserDetails = new BindingSource();
//info stored in tables
DataSet dsUserDetails = new DataSet();
//manages connection between database and application
SqlDataAdapter daUserDetails = new SqlDataAdapter();
//create new SQL connection
SqlConnection connUserDetails = new SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=D:\Users\synthesis\Documents\Visual Studio 2010\Projects\Practical\Practical\App_Data\UserDetails.mdf;Integrated Security=True;User Instance=True");
protected void Page_Load(object sender, EventArgs e)
{
//link textboxes to relevant fields in the dataset
bsUserDetails.DataSource = dsUserDetails;
bsUserDetails.DataMember = dsUserDetails.Tables[0].ToString();
//call BindTextBoxes Method
BindTextBoxes();
private void BindTextBoxes()
{
txtBoxCell.DataBindings.Add(new Binding("Name entered into txtBox", bsUserDetails,
"Name column in database table", true));
}
}
}
You could always write your own SQL for inserting data from your text boxes. You'll need to setup a SqlConnection and SqlCommand object. Then you'll need to define the SQL on the command and set up the parameters to prevent SQL injection. Something like this:
StringBuilder sb = new StringBuilder();
sb.Append("INSERT INTO sometable VALUES(#text1,#text2)");
SqlConnection conn = new SqlConnection(connStr);
SqlCommand command = new SqlCommand(sb.ToString());
command.CommandType = CommandType.Text;
command.Parameters.AddWithValue("text1", text1.Text);
command.Parameters.AddWithValue("text2", text2.Text);
command.ExecuteNonQuery();

Categories