Creating Dataset Dynamically and passing to ReportViewer - c#

all i did is just create a reportViewer in the form, then i have this code:
SqlConnection cn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=G:\I.S\C#\billingSystem\Store.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
private void Form1_Load()
{
runRptViewer();
cn.Open();
}
private void rptGetDataset()
{
DataSet ds = new DataSet();
ds.DataSetName = "dsNewDataSet";
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM NewBill", cn);
ds.GetXmlSchema();
da.Fill(ds);
ds.WriteXmlSchema(#"G:\I.S\Testoooooooo\Testoooooooo\Dataset1.xsd");
ds.WriteXml(#"G:\I.S\Testoooooooo\Testoooooooo\Dataset1.xml");
}
private DataTable getData()
{
DataSet dss = new DataSet();
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM NewBill", cn);
da.Fill(dss);
DataTable dt = dss.Tables["NewBill"];
return dt;
}
private void runRptViewer()
{
this.reportViewer2.Reset();
//this.ReportViewer1.LocalReport.ReportPath = Server.MapPath("Report.rdlc");
this.reportViewer2.LocalReport.ReportPath =(#"G:\I.S\Testoooooooo\Testoooooooo\Report1.rdlc");
ReportDataSource rds = new ReportDataSource("dsNewDataSet_NewBill", getData());
this.reportViewer2.LocalReport.DataSources.Clear();
this.reportViewer2.LocalReport.DataSources.Add(rds);
//this.reportViewer2.DataBind();
this.reportViewer2.LocalReport.Refresh();
}
}
i have two reportViewer the reportViewer1 work but in case the directory of the db has change it will not work, so thats why i try in another reportViewer, to make it work even if the directory of the db changed, i can just change the Connection string.
The problem is the report don't show anything, i think the problem in the code:
//this.ReportViewer1.LocalReport.ReportPath = Server.MapPath("Report.rdlc");
this is a windows form so there is no server, ive change it to:
this.reportViewer2.LocalReport.ReportPath =(#"G:\I.S\Testoooooooo\Testoooooooo\Report1.rdlc");
and this one dont work:
//this.reportViewer2.DataBind();
i cant understand this two lines, does it mean to create a Dataset1.xsd and Dataset1.xml, or just edit them.
ds.WriteXmlSchema(#"G:\I.S\Testoooooooo\Testoooooooo\Dataset1.xsd");
ds.WriteXml(#"G:\I.S\Testoooooooo\Testoooooooo\Dataset1.xml");
if possible i need a steps from creating every thing to codding that will be great.

How did you create your dataset? Is it SQL or from Objects in memory?
If you havent created a dataset, you do need to create one before the report can work properly. This might help: http://shrutikapoor-ubc.blogspot.com/2013/05/using-business-objects-in-report-viewer.html

To use the report viewer in your C# WinForm project add the following code to a button or inthe form_load:
string strConnectionString = "Data Source=(local);Initial Catalog=Projects_DB;Integrated Security=True";
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter();
SqlCommand cmd = new SqlCommand("sp_GetProject " + "'0660CAD6-6F1A-4D19-A1FD-17BF3655AC98'");
cmd.CommandType = CommandType.Text;
cmd.Connection = new SqlConnection (strConnectionString);
da.SelectCommand = cmd;
da.Fill(ds,"DataSet1");
reportViewer1.ProcessingMode = ProcessingMode.Local;
reportViewer1.LocalReport.DataSources.Clear();
reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("DataSet1", ds.Tables[0]));
reportViewer1.LocalReport.Refresh();
reportViewer1.RefreshReport();
Assuming that you have a stored procedure that accepts #ProjectID parameter. You have to set the cmd.CommandType = CommandType.Text if you pass these parameters along with the sql command. However, if you don't want to pass parameters just change the commandType to cmd.CommandType = CommandType.StoredProcedure.
Below is the stored procedure used in this example:
CREATE PROC [dbo].[sp_GetProject]
#ProjectID nvarchar(50)=NULL
AS
BEGIN
SELECT ProjectID, ProjectName FROM Projects
WHERE
(#ProjectID IS NULL) OR (ProjectID = #ProjectID)
END

Microsoft has a pretty good walkthrough here...
http://blogs.msdn.com/b/sqlforum/archive/2011/04/28/sql-reporting-services-ssrs-bind-dynamic-dataset-to-your-local-report-with-reportviewer.aspx

Related

RDLC issue with mutiple datasets Winform project in c#

I'm building a report in report viewer. With a single dataset, it works great but I need to include in this same report, mutiple datasets. Can you tell me what i'm doing wrong please (with some code if possible). I found a whole bunch of info on this issue but everything is not in the same programming language. I'm using C#. In the .RDLC, I have one datasource created and 2 datasets (DataSet and DataSet1). Here is my current code:
private void LoadReport()
{
try
{
MySqlConnection con = new MySqlConnection(conSettings.ToString());
MySqlCommand cmd = new MySqlCommand("packing_slips", con);
MySqlCommand cmd1 = new MySqlCommand("client_info", con);
con.Open();
cmd.Parameters.Add("#project", MySqlDbType.VarChar, 20).Value = project_id_box.Text;
cmd.CommandType = CommandType.StoredProcedure;
cmd1.Parameters.Add("#project", MySqlDbType.VarChar, 20).Value = project_id_box.Text;
cmd1.CommandType = CommandType.StoredProcedure;
MySqlDataAdapter adp = new MySqlDataAdapter(cmd);
MySqlDataAdapter adp1 = new MySqlDataAdapter(cmd1);
DataSet ds = new DataSet();
DataSet ds1 = new DataSet();
adp.Fill(ds);
adp1.Fill(ds1);
reportViewer1.Reset();
this.reportViewer1.LocalReport.DataSources.Clear();
ReportDataSource reportDataSource = new ReportDataSource();
reportDataSource.Value = ds.Tables[0];
reportDataSource.Name = "DataSet";
ReportDataSource reportDataSource1 = new ReportDataSource();
reportDataSource1.Value = ds1.Tables[0];
reportDataSource1.Name = "DataSet1";
this.reportViewer1.LocalReport.DataSources.Add(reportDataSource);
this.reportViewer1.LocalReport.DataSources.Add(reportDataSource1);
this.reportViewer1.LocalReport.ReportPath = "project_report.rdlc";
this.packing_slipsTableAdapter.Fill(this.shopmanagerDataSet.packing_slips);
this.projectsTableAdapter.Fill(this.shopmanagerDataSet.projects);
this.reportViewer1.RefreshReport();
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I'm not getting any compile errors when compiling but the report is blank. I'm retreiving the data from a MySQL db with stored procedures. When debugging i'm seeing that ds and ds1 are getting populated correctly. Thanks.
I found the answer. When adding mutiple datasets to a RDLC, you need to specify from what dataset the information is coming from in the textbox properties. EG:
=First(Fields!project_number.Value, "DataSet")
That fixed it for me. The code above is good for anyone else having this issue.

SQLConnection bringing data to TextBox

I know this looks really simple but i've been looking for an answer for hours with no luck.
I want to fill my row values into a bunch of textboxes. How can I specify that [CompanyName] is going to be used by the companyName textbox? Please keep it as simple as possible (beginner level).
string customerUniqueID = "test";
string constr = ConfigurationManager.ConnectionStrings["SQLConnection"].ToString(); // connection string
SqlConnection con = new SqlConnection(constr);
con.Open();
SqlCommand com = new SqlCommand("SELECT * FROM [Customers] WHERE [UniqueID] = #UniqueID", con); // table name
com.Parameters.Add("#UniqueID", SqlDbType.Int);
com.Parameters["#UniqueID"].Value = customerUniqueID;
SqlDataAdapter da = new SqlDataAdapter(com);
DataSet ds = new DataSet();
companyName.Text = ?????????
string customerUniqueID = "test";
string constr = ConfigurationManager.ConnectionStrings["SQLConnection"].ToString(); // connection string
SqlConnection con = new SqlConnection(constr);
con.Open();
SqlCommand com = new SqlCommand("SELECT * FROM [Customers] WHERE [UniqueID] = #UniqueID", con); // table name
com.Parameters.Add("#UniqueID", SqlDbType.Int);
com.Parameters["#UniqueID"].Value = customerUniqueID;
SqlDataAdapter da = new SqlDataAdapter(com);
DataSet ds = new DataSet();
da.Fill(ds, "Customers");
companyName.Text = ds.Tables[0].Rows[0]["CompanyName"].ToString();
I will recommend some changes in your code:
Your sql query returning result from one set, so you can use DataTabe instead of DataSet.
To fill results from DB to your DataTable you can use SqlAdapter.Fill() method.
Use Field() generic method (more examples of Field()) to get values from your DataTable.
Use using blocks for disposable objects, or at least make sure you've closed them after.
There is no need of con.Open() to open connection when using Fill() method, because from MSDN:
The Fill method implicitly opens the Connection that the DataAdapter is using if it finds that the connection is not already open. If Fill opened the connection, it will also close the connection when Fill is finished. This can simplify your code when dealing with a single operation such as a Fill or an Update.
string customerUniqueID = "test";
string constr = ConfigurationManager.ConnectionStrings["SQLConnection"].ToString(); // connection string
using(SqlConnection con = new SqlConnection(constr))
{
SqlCommand com = con.CreateCommand();
com.CommandText = "SELECT * FROM [Customers] WHERE [UniqueID] = #UniqueID";
com.Parameters.Add("#UniqueID", SqlDbType.Int);
com.Parameters["#UniqueID"].Value = customerUniqueID;
using(SqlDataAdapter da = new SqlDataAdapter(com))
{
DataTable dt = new DataTable();
da.Fill(dt);
companyName.Text = dt.Rows[0].Field<string>("CompanyName");
}
}
Please feel free to comment, if I missed something.

ASP.NET local SQL Server database C# gridview data binding Visual Studio 2013

I need some help because I've been trying different things but nothing seems to work properly the question itself is the one below.
How can I bind data to a grid-view in Visual Studio 2013 with a local SQL Server database using the code behind C# ?
Here is the C# I'm trying:
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Guillermo\Desktop\HorsensHospital\App_Data\HospitalDB.mdf;Integrated Security=True;Connect Timeout=30");
con.Open();
SqlCommand cmd = new SqlCommand("SELECT [Task_temp_name], [Task_templatesID] FROM [Task_templates]", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
GridView1.DataSource = ds;
GridView1.DataBind();
cmd.ExecuteNonQuery();
con.Close();
}
You just assing your empty DataSet to your Gridview's DataSource.
You need to use .Fill method fo fill your DataSet of SqlDataAdapter. You don't need to use ExecuteNonQuery. This method just executes your query. It doesn't return any data or something as a result.
Also use using statement to dispose your SqlConnection, SqlCommand and SqlDataAdapter. You don't need to .Close() your database connections and objects when you use it.
using(SqlConnection con = new SqlConnection(conString))
using(SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "SELECT [Task_temp_name], [Task_templatesID] FROM [Task_templates]";
using(SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
DataSet ds = new DataSet();
sda.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
You should use statement like this :
when you use SqlDataAdapter you should fill an dataset with Fill Method
then set the DataSource Properties Of GridView
SqlCommand cmd = new SqlCommand("SELECT [Task_temp_name], [Task_templatesID] FROM [Task_templates]", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
con.Close();
You have missed Fill method to fill your your dataset that is why i think you are not able to display gridview.
Fill Method is very Improtant method Bcoz whatever your query is returning that should be filled into your dataset & then that dataset is binded by your Gridiview
Hope this will help you
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Guillermo\Desktop\HorsensHospital\App_Data\HospitalDB.mdf;Integrated Security=True;Connect Timeout=30");
con.Open();
SqlCommand cmd = new SqlCommand("SELECT [Task_temp_name], [Task_templatesID] FROM [Task_templates]", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sda.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
cmd.ExecuteNonQuery();
con.Close();
}
Note : You need to create your connection string in Web.Config. Bcoz If you have created your connection string there then you will not need to create that again. Once creating there you will just need to call that from the Web.config
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionStringNameFromWebConfig"].ConnectionString);
This is the syntax for calling connection string from web.config

Returning a Dataset as an Object in a Method

I am writing a method that will query a table and return a Dataset object containing the specified column. Moreover, I have a problem with my Username & Password, so I am using Windows authentication for the same but I am not too sure about that in my snippet I have written till now.
protected void GetProgramList()
{
SqlConnection cn = new SqlConnection("server=Daffodils-PC/sqlexpress;Database=Assignment1;Trusted_Connection=Yes;");
SqlCommand cmd = new SqlCommand("SELECT ProgramName FROM Program", cn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet1 ds1 = new DataSet1();
}
I have been trying to follow official MS documentation but I am not sure where I am going? Can someone help me with some links or snippets?
I would say you have 2 options here:
1. to make a DataSet class variable, so its reference can be accessed from all over the class (set its access modifier to public so it can be accessed from other classes)
2. or create a method with its return type of DataSet. But in this case on the other side must be set to receive the DataSet as well:
//2. solution:
private void GetData()
{
//from inside some method:
DataSet ds = GetProgramList();
}
protected DataSet GetProgramList()
{
DataSet ds1 = new DataSet();
using (SqlConnection cn = new SqlConnection("server=Daffodils-PC/sqlexpress;Database=Assignment1;Trusted_Connection=Yes;"))
{
using (SqlDataAdapter da = new SqlDataAdapter(#"SELECT ProgramName FROM Program", cn))
da.Fill(ds1, "TableName1");
}
return ds1;
}
//
//1. solution:
class YourClass
{
DataSet ds1;
protected void GetProgramList()
{
SqlConnection cn = new SqlConnection("server=Daffodils-PC/sqlexpress;Database=Assignment1;Trusted_Connection=Yes;");
SqlCommand cmd = new SqlCommand("SELECT ProgramName FROM Program", cn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
ds1 = new DataSet();
}
}
Place your connection string in AppSettings section in app.config or web.config
public string GetSqlConnection()
{
return System.Configuration.ConfigurationManager.AppSettings["SqlConnectionString"];
}
public DataSet getDataSet(string sql)
{
DataSet ds = new DataSet();
SqlConnection conn = new SqlConnection(GetSqlConnection());
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
da.Fill(ds);
conn.Close();
conn.Dispose();
da.Dispose();
return ds;
}
Suggestion: "use" System.Data and System.Data.SqlClient, and use a "SqlDataReader":
http://www.csharp-station.com/Tutorial/AdoDotNet/lesson04
Either read everything in your routine (generally preferred), or pass the SqlDataReader back to the caller (as a function return).
And be sure to .Close() the reader when you're done :)
SQLDataAdapter basic will get you started with the basics of creating a connection and consuming it in your code.

problem with mysql stored procedure when working in C# Visual Studio

I'm new to MySQL and now i hava a project which must work with MYSQL. It's a win application and I use C# on Visual Studio 2010. I tried to write a simple stored procedure like this:
DELIMITER $$
CREATE DEFINER=`root`#`localhost` PROCEDURE `GetBank`()
BEGIN
SELECT * FROM BANKNAME;
END
And my C# code is here:
private void btnShow_Click(object sender, EventArgs e)
{
MySqlConnection con = new MySqlConnection("SERVER=localhost;DATABASE=dowacodb;UID=root;PASSWORD=123456");
con.Open();
DataTable dt = new DataTable();
MySqlCommand cm = new MySqlCommand("GetBank", con);
cm.CommandType = CommandType.StoredProcedure;
MySqlDataAdapter da = new MySqlDataAdapter(cm);
da.Fill(dt);
con.Close();
dataGridView1.DataSource = dt;
}
My test is to show the data in datagridview when clicking the button. It shows fine on the first click but when I click again, the data in datagridview is gone. The next click will show the data again and repeatedly.
But this code will be perfect when not working with stored procedured
private void btnShow_Click(object sender, EventArgs e)
{
MySqlConnection con = new MySqlConnection("SERVER=localhost;DATABASE=dowacodb;UID=root;PASSWORD=123456");
con.Open();
DataTable dt = new DataTable();
MySqlCommand cm = new MySqlCommand("Select * from bankname", con);
cm.CommandType = CommandType.Text;
MySqlDataAdapter da = new MySqlDataAdapter(cm);
da.Fill(dt);
con.Close();
dataGridView1.DataSource = dt;
}
So what's wrong with MySQL? Thanks in advance
The syntax to call your procedure in MySQL is
CALL GetBank()
so
MySqlCommand cm = new MySqlCommand("CALL GetBank()", con);
should do it. Which also removes the need to specify that your command cm is a stored procedure.
This problem is solved! Instead of using ordinary way to interact with MySQL: open a connection, create a command and use a data adapter to fill datatable, I use a MySQLHelper class and it works fine for me:
DataTable dt = MySqlHelper.ExecuteDataset("SERVER=localhost;DATABASE=dowacodb;UID=root;PASSWORD=123456", "call getbank()").Tables[0];
dataGridView1.DataSource = dt;
But now I wonder why this way works while the older way doesn't ?

Categories