C# chart control populate with stored procedure with parameters - c#

enter image description hereI can populate chart control in C# Winforms with stored procedures without parameters and that's fine. But now I need to use stored procedure with parameters. Any advice how to do that?
Below is my code how i am populating chart control with stored procedure without parameters.
sqlCon.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = sqlCon;
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter myCommand = new SqlDataAdapter("[Proc1]", sqlCon);
DataSet ds = new DataSet();
myCommand.Fill(ds);
DataView source = new DataView(ds.Tables[0]);
chart1.DataSource = source;
chart1.ChartAreas["ChartArea1"].AxisX.Interval = 1;
chart1.Series[0].XValueMember = "Pojazd";
chart1.Series[0].YValueMembers = "Suma";
chart1.DataBind();
Please help me :-)

Just a further explanation of what #Rakitić said.
SqlCommand cmd = new SqlCommand();
cmd.Parameters.Add("#PARAMNAME", SqlDbType.VarChar,10).Value = paramValue;
Then you'll need to add this parameter within your stored procedure. Which I'm just guessing you're using Sql Server:
#PARAMNAME varchar(10)

Related

How to use DataAdapter to call a stored procedure in C# with variable parameters

I am calling the following code in C# to fill a dataAdapter with a given stored procedure "sp1_name". The problem is that I want to call different stored procedures with different parameters. (All SP's do a SELECT)
Let's suppose that my stored procedure name is "SP_SOMESP", then everything works fine.
Let's suppose that my stored procedure name is "SP_SOMESP #Month= 10, #Year = 2010", then it doesn't work. It throws an exception that cannot find this stored procedure.
Any solutions?
Thanks!
//First Connection - SP1
using (SqlConnection con = new SqlConnection(conStr))
{
using (SqlCommand cmd = new SqlCommand(sp1_name, con)) //sp1_name = NAME + PARAMETERS
{
cmd.CommandTimeout = 3600;
cmd.CommandType = CommandType.StoredProcedure;
using (SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd))
{
dataAdapter.Fill(results2);
}
}
}
First Issue:
Parameters in a stored procedure shouldn't be included along with its name
Second Issue:
Having a space in names of stored procedure isn't a good practice.
And for code behind
using(SqlConnection con = new SqlConnection("Your Connection String Here"))
{
SqlCommand cmd = new SqlCommand("sp_SomeName", con);
cmd.CommandType = CommandType.StoredProcedure;
//the 2 codes after this comment is where you assign value to the parameters you
//have on your stored procedure from SQL
cmd.Parameters.Add("#MONTH", SqlDbType.VarChar).Value = "someValue";
cmd.Parameters.Add("#YEAR", SqlDbType.VarChar).Value = "SomeYear";
SqlDataAdapter da = new SqlDataAdapter(cmd);
SqlDataSet ds = new SqlDataSet();
da.Fill(ds); //this is where you put values you get from the Select command to a
//dataset named ds, reason for this is for you to fetch the value from DB to code behind
foreach(DataRow dr in ds.Tables[0].Rows) // this is where you run through the dataset and get values you want from it.
{
someTextBox.Text = dr["Month"].ToString(); //you should probably know this code
}
}
You have to add in the parameters programmatically, see SqlCommand.Parameters.
It would be something like
cmd.Parameters.AddWithValue("#Month", 10);
cmd.Parameters.AddWithValue("#Year", 2010);
This would be after the command is declared and before it is executed.
If you find that you need to delcare the data type, then try it this way
cmd.Parameters.Add("#Month", SqlDbType.Int).Value = 10;
Check this,
using (SQLCommand cmd = new SQLCommand())
{
cmd.CommandText = "SP_SOMESP";
cmd.Parameters.Add("#Month", 10);
cmd.Parameters.Add("#Year", 2010);
cmd.CommandTimeout = 3600;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
}
using (SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd))
{
dataAdapter.SelectCommand = cmd;
dataAdapter.Fill(results2);
}

C# and SQL Server: How do I get values from my SQL Table, by calling my stored procedure with C#?

I created the following stored procedure
CREATE PROCEDURE dbo.GetPoint
AS
SELECT point FROM tLocalGeo
Now I need execute that procedure from my C# Controller and save the data on a list.
As you can see the context of the problem is to get points so then I can display them on google map using javascript for that.
Can you give me some reference how to do it? Do I need SQLReader?
Thank you for your attention.
You can use SqlDataAdapter and DataSet and then can get values from dataset's first table.
SqlCommand cmd = new SqlCommand("store procedure Name", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapter= new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adapter.Fill(ds);
if(ds.Tables[0]!=null && ds.Tables[0].Rows.Count > 0)
{
//your code
}
Hope it helps.
String strConnString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "GetPoint";
cmd.Parameters.AddWithValue("#EmployeeID", Empid) // ur input parameter//
cmd.Connection = con;
try
{
con.Open();
GridView1.EmptyDataText = "No Records Found";
GridView1.DataSource = cmd.ExecuteReader() ;
GridView1.DataBind();
}

Creating Dataset Dynamically and passing to ReportViewer

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

Procedure or function [sproc_name] expects parameter '#materials', which was not supplied

This is driving me nuts ;)
I have this stored procedure ...
ALTER PROCEDURE [dbo].[sproc_FindFoundries]
(#materials varchar(1000),
#capabilities varchar(1000))
AS
BEGIN
/* insert SQL code here */
END
The procedure accepts two comma delimited strings. In my application I have the following code.
BCDataContext db = new BCDataContext();
SqlParameter prmMaterials = new SqlParameter("materials", SqlDbType.VarChar, 1000);
prmMaterials.Value = materialList;
SqlParameter prmCapability = new SqlParameter("capabilities", SqlDbType.VarChar, 1000);
prmCapability.Value = capabilityList;
SqlConnection cn = new SqlConnection(db.Connection.ConnectionString);
SqlCommand cmd = new SqlCommand("sproc_FindFoundries", cn);
cmd.Parameters.Add(prmMaterials);
cmd.Parameters.Add(prmCapability);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
When I execute the code, I get the error
Procedure or function [sproc_name] expects parameter '#materials', which was not supplied.
when I try fill the dataset. When testing I have verified that both parameters contain data and are not null. Is there something I've missed? A second pair of eyes would be greatly appreciated.
Thanks.
Use #materials, #capabilities as parameters' name:
using (BCDataContext db = new BCDataContext())
using (SqlConnection connection = new SqlConnection(db.Connection.ConnectionString))
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = "sproc_FindFoundries";
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("#materials", SqlDbType.VarChar, 1000).Value = materialList;
command.Parameters.Add("#capabilities", SqlDbType.VarChar, 1000).Value = capabilityList;
DataSet ds = new DataSet();
using (SqlDataAdapter da = new SqlDataAdapter(command))
{
da.Fill(ds);
}
}
When naming your parameters you need to put the # in
SqlParameter prmMaterials = new SqlParameter("#materials", SqlDbType.VarChar, 1000)
You are calling your parameters "materials" and "capabilities" instead of "#materials" and "#capabilities"
I tried like this, Its worked for me:
int deal_id = 25;
_dbContext.Database.ExecuteSqlCommand("exec sp_getdeal #deal_id={0}", deal_id);
My procedure is like this:
ALTER PROCEDURE [dbo].[sp_getdeal]
(
#deal_id INTEGER
)
AS
BEGIN

Working with a QueryString and placing value in Stored Procedure?

I am working with ASP.NET and SQL Server 2005.
I know how to create a stored proceudre but i do not know what to place in a stored procedure when i need to make use of a QueryString.
My SQL Statement in CODE =
"SELECT * FROM TableName WHERE ID = '" + Request.QueryString("ID") + "'"
Now what must i place in my stored procedure to get this to work? I want to call a stored procedure and thus do not want to use this code in my code behind.
Thanks in advance!
Create an sqlcommand object
set the commandtext = "StoredProcName"
add an sqlParameter with the name of your sproc parameter - set its type
set its value to Request.QueryString("ID")
check this out for full instructions:
http://support.microsoft.com/kb/306574
Try the following code:
SqlCommand mycommand = new SqlCommand("yourstoredproc", con);
mycommand.CommandType = CommandType.StoredProcedure;
mycommand.Parameters.AddWithValue("#yourparam", Request.QueryString["ID"]);
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = mycommand;
DataSet dataset = new DataSet();
adapter.Fill(dataset);
SqlCommand cmd = new SqlCommand("storedprocedure_name",con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#parameter_of-procedure",Request.QueryString"ID"]);
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = mycommand;
DataSet dataset = new DataSet();
adapter.Fill(dataset);
//using sqldatareader
SqlCommand cmd = new SqlCommand("yourstoredproc", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#parameters_of_procedure",Request.QueryString["ID"]);
con.open()
sqldatareader dr=cmd.executereader();
gridview1.datasouce=dr;
gridview1.databind();
con.close();
The answer for this problem is located here

Categories