Gridview datasource from database stored procedure - c#

This is the database stored procedure:
ALTER PROCEDURE [dbo].[getShift]
#rfiddata VARCHAR(50)
AS
BEGIN
SELECT
pd.TP, s.s_name, dt.dt_type, dr.dr_date
FROM
TA_System_PersonalDetails pd
INNER JOIN
TA_System_DutyRequest dr ON pd.TP = DR.TP
INNER JOIN
TA_System_Duty d ON dr.d_ID = d.d_ID
INNER JOIN
TA_System_Shift s ON d.s_ID = s.s_ID
INNER JOIN
TA_System_DutyType dt ON d.dt_ID = dt.dt_ID
WHERE
pd.rfid_card = #rfiddata
AND dr.dr_date = CAST(GETDATE() AS DATE)
END
And this the C# code:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("dbo.getShift", con);
cmd.Parameters.AddWithValue("#rfiddata", data);
cmd.CommandType = CommandType.StoredProcedure;
gvDetails.DataSource = cmd.ExecuteNonQuery();
con.Close();
The gridview still not able to show the value. And this project is in windows form C#. Hence, there is no DataBind() function. Thanks in advance for the help!

I hope this code will help
First we create a connector to connect to the database
string cnStr = #"Persist Security Info=False;User ID=usr;password=pwe; Initial Catalog=theDataBase;Data Source=yourDatasource";
and create a SqlCommand and after set the CommandType to StoredProcedure:
SqlCommand cmd = new SqlCommand();
Then create a SqlConnection and Open Database:
using(SqlConnection con = new SqlConnection(cnStr))
{
con.Open();
cmd.Connection = con;
cmd.CommandText = "dbo.getShift"; // this is the stored procedure to execute
cmd.CommandType = CommandType.StoredProcedure;
}//Connection automatically closes here without the need to call conn.Close()
Then create a dataset to be filled as the datasource for the gridview:
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
grdYourGrid.DataSource = ds;
grdYourGrid.DataBind();

Related

It doesn't return rows store from c#

I am working with Oracle and C#, when I run my stored procedure from C#, it doesn't return any results. I don't know if it is my stored procedure that I am doing it wrong or my code but it does not return results.
C# code
public DataTable ObtenerInformacion(string SEC)
{
using (OracleConnection cn = new OracleConnection("CONNECTION LIFETIME=10;DATA SOURCE=AAA;MAX POOL SIZE=10;PASSWORD=AAA;PERSIST SECURITY INFO=True;USER ID=AAA"))
{
OracleDataAdapter da = new OracleDataAdapter();
OracleCommand cmd = new OracleCommand();
cmd.Connection = cn;
cmd.InitialLONGFetchSize = 1000;
cmd.CommandText = "sp_student";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("SEQ", OracleDbType.Varchar2).Value = SEC;
da.SelectCommand = cmd;
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
}
Stored procedure code in Oracle
CREATE OR REPLACE Procedure sp_student(SEQ IN VARCHAR2)
as
SEQUENCIA transaction.SEQ%Type;
IMPORTE100 transaction.AMOUNT_BEFORE_DISCOUNT%Type;
IMPORTEDESC transaction.AMOUNT_REAL%Type;
Begin
SELECT SEQ,AMOUNT_BEFORE_DISCOUNT, AMOUNT_REAL INTO SEQUENCIA,IMPORTE100,IMPORTEDESC FROM transaction WHERE SEQ=SEQ;
end;

Populate a list view in asp.net winform by using stored procedure with parameters through a button click

In my Winforms application, I have to do search by using three parameters. I retrieve from the database by using stored procedure. But an exception is thrown:
Procedure or function 'sp_searchProduct' expects parameter '#categoryId', which was not supplied
Kindly help me.
This is my code:
private void button2_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=DESKTOP-U1OP1S9\SQLEXPRESS;Initial Catalog=PaintStores;Integrated Security=True");
SqlCommand command = new SqlCommand("sp_searchProduct", con);
command.Parameters.AddWithValue("#categoryId", comboBox1.SelectedValue.ToString());
command.Parameters.AddWithValue("#typeId", comboBox2.SelectedValue.ToString());
command.Parameters.AddWithValue("#productId", comboBox3.SelectedValue.ToString());
SqlDataAdapter da = new SqlDataAdapter(command);
DataTable dataTable = new DataTable();
da.Fill(dataTable);
for (int i = 0; i < dataTable.Rows.Count; i++)
{
DataRow drow = dataTable.Rows[i];
if (drow.RowState != DataRowState.Deleted)
{
ListViewItem lvi = new ListViewItem(drow["ProductId"].ToString());
lvi.SubItems.Add(drow["ProductName"].ToString());
lvi.SubItems.Add(drow["TypeName"].ToString());
lvi.SubItems.Add(drow["Quantity"].ToString());
lvi.SubItems.Add(drow["Price"].ToString());
lvi.SubItems.Add(drow["Stock"].ToString());
listView1.Items.Add(lvi);
}
}
con.Close();
}
This is my stored procedure:
ALTER PROCEDURE [dbo].[sp_searchProduct]
#categoryId INT,
#typeId INT,
#productId INT
AS
IF (#categoryId = 0)
BEGIN
SET #categoryId = NULL
END
IF (#typeId = 0)
BEGIN
SET #typeId = NULL
END
IF (#productId = 0)
BEGIN
SET #productId = NULL
END
BEGIN
SET NOCOUNT ON;
SELECT p.ProductId, p.ProductName, p.Quantity, p.Price, p.Stock
FROM tblProductNew p
INNER JOIN tblTypes t ON t.TypeId = p.TypeId
WHERE p.ProductId = ISNULL(#productId, p.ProductId)
AND p.TypeId = ISNULL(#typeId, p.TypeId)
AND t.MainCategoryId = ISNULL(#categoryId, t.MainCategoryId)
END
Make sure you add this to your code before calling da.Fill(dataTable);
command.CommandType = CommandType.StoredProcedure;
Your final code should look something like this..
SqlConnection con = new SqlConnection(#"Data Source=DESKTOP-U1OP1S9\SQLEXPRESS;Initial Catalog=PaintStores;Integrated Security=True");
SqlCommand command = new SqlCommand("sp_searchProduct", con);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("#categoryId",comboBox1.SelectedValue.ToString());
There are two mistakes. One is you should specify command type. Second is, SP expects categoryId as int and you're converting it into string.
SqlConnection con = new SqlConnection(#"Data Source=DESKTOP-U1OP1S9\SQLEXPRESS;Initial Catalog=PaintStores;Integrated Security=True");
SqlCommand command = new SqlCommand("sp_searchProduct", con);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("#categoryId", comboBox1.SelectedValue);
command.Parameters.AddWithValue("#typeId", comboBox2.SelectedValue);
command.Parameters.AddWithValue("#productId", comboBox3.SelectedValue);
SqlDataAdapter da = new SqlDataAdapter(command);
DataTable dataTable = new DataTable();
da.Fill(dataTable);
The mistake is I missed to clear the earlier results in the list view. I use the line listView1.Items.Clear(); before I insert the queried results to the list view. Now the error gone.

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();
}

Calling a SP which has Insert Statement and returns a table

Is it possible to call a stored procedure which will insert the details first and at the end will return a table. At present I have written two stored procedures for it: one for inserting and the other for getting the details. Now I'm trying to do both at the same time.
I'm using ExecuteScalar for inserting and ExecuteDataSet for selecting.
If your stored procedure returns data using a SELECT (of course, I suppose that you need to read that data) then you should use the SqlDataAdapter with its Fill method or an SqlDataReader using the ExecuteReader on the SqlCommand
ExecuteReader:
using(SqlConnection cn = new SqlConnection(...))
using(SqlCommand cmd = new SqlCommand(procName, cn))
{
cmd.CommandType = CommandType.StoredProcedure;
cn.Open()
using(SqlDataReader r = cmd.ExecuteReader())
{
while(r.Read())
{
// read every row and use the field values .....
}
}
}
SqlDataAdapter.Fill:
using(SqlConnection cn = new SqlConnection(...))
using(SqlCommand cmd = new SqlCommand(procName, cn))
{
cmd.CommandType = CommandType.StoredProcedure;
cn.Open()
using(SqlDataAdapter da = new SqlDataAdapter(cmd)
{
DataTable dt = new DataTable();
da.Fill(dt);
// DataTable filled with the data returned by the last SELECT in your SP
......
}
}
The SqlCommand.ExecuteReader or SqlDataAdapter.Fill will execute the stored procedure without looking at what the stored procedure does, but they expect that some kind of tabular data will be returned to loop over it
You write a procedure like this
CREATE PROCEDURE SP_Name
(
//PARAMETES
)
AS
BEGIN
//INSERT STATEMENT
//SELECT STATEMENT
END
and call ExecuteDataSet()
SqlConnection cn = new SqlConnectio(...)
SqlCommand cmd = new SqlCommand("procName", cn)
{
cmd.CommandType = CommandType.StoredProcedure;
cn.Open();
cmd.ExecuteScalar();
}

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