Currently, my program in Visual Studio dynamically adds my data from my Repeater into my database.
Now I need to add the ID, my EventId and FormId, which I collected manually outside of the Repeater.
I need to add this in:
sqlCmd.Parameters.Add("#EventId", SqlDbType.Int).Value = eventId;
sqlCmd.Parameters.Add("#FormId", SqlDbType.Int).Value = formId;
However with how my code is setup, it gives an error when I add this code that says:
Additional information: Procedure or function 'spInsFormRegistrant'
expects parameter '#EventId', which was not supplied.
Working code (with error code commented out):
protected void BtnSubmit_Click(object sender, EventArgs e)
{
using (SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["Events2"].ConnectionString))
{
sqlConn.Open();
using (SqlCommand sqlCmd = new SqlCommand())
{
//sqlCmd.Parameters.Add("#EventId", SqlDbType.Int).Value = eventId;
//sqlCmd.Parameters.Add("#FormId", SqlDbType.Int).Value = formId;
foreach (RepeaterItem rpItem in RepeaterForm.Items)
{
Label lblDisplayName = rpItem.FindControl("lblDisplayName") as Label;
Label lblColumnName = rpItem.FindControl("lblColumnName") as Label;
TextBox txtColumnValue = rpItem.FindControl("txtColumnValue") as TextBox;
if (txtColumnValue != null)
{
sqlCmd.Connection = sqlConn;
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.CommandText = "spInsFormRegistrant";
sqlCmd.Parameters.Clear();
sqlCmd.Parameters.Add("#ColumnName", SqlDbType.NVarChar).Value = lblColumnName.Text;
sqlCmd.Parameters.Add("#ColumnValue", SqlDbType.NVarChar).Value = txtColumnValue.Text;
sqlCmd.ExecuteNonQuery();
}
}
}
}
PnlNone.Visible = false;
PnlExist.Visible = false;
PnlSuccess.Visible = true;
PnlFail.Visible = false;
}
So I just need to know where to add in #EventId and #FormId for this to function correctly. Each time I try it, it does not work. I must be missing something small for this to not produce an error. Or maybe it is an issue with my stored procedure...?
Stored Procedure
ALTER PROCEDURE [dbo].[spInsFormRegistrant]
-- Add the parameters for the stored procedure here
#EventId int,
#FormId int,
#ColumnName varchar(100),
#ColumnValue varchar(100)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
declare #Query nvarchar(4000)
declare #ParmDefinition nvarchar(500);
set #Query = 'INSERT into Registrant(DateCreated,EventId,FormId,'+ (#ColumnName) +') values (CURRENT_TIMESTAMP, #EventId, #FormId, #ColumnValue)'
set #ParmDefinition = N'#ColumnValue varchar(100)'
exec sp_executesql #Query, #ParmDefinition, #ColumnValue = #ColumnValue
END
You are not adding the parameter for eventID and for FormID, but you should try to use a different approach. Do not create everytime the parameters. You could create them just one time before entering the foreach loop and then, inside the loop change only their value
// This part never changes so, set it up just one time before the loop
sqlCmd.Connection = sqlConn;
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.CommandText = "spInsFormRegistrant";
sqlCmd.Parameters.Add("#EventId", SqlDbType.Int).Value = eventId;
sqlCmd.Parameters.Add("#FormId", SqlDbType.Int).Value = formId;
// These twos change inside the loop, so we don't need the value here
sqlCmd.Parameters.Add("#ColumnName", SqlDbType.NVarChar);
sqlCmd.Parameters.Add("#ColumnValue", SqlDbType.NVarChar);
foreach (RepeaterItem rpItem in RepeaterForm.Items)
{
Label lblDisplayName = rpItem.FindControl("lblDisplayName") as Label;
Label lblColumnName = rpItem.FindControl("lblColumnName") as Label;
TextBox txtColumnValue = rpItem.FindControl("txtColumnValue") as TextBox;
if (txtColumnValue != null)
{
sqlCmd.Parameters["#ColumnName"].Value = lblColumnName.Text;
sqlCmd.Parameters["#ColumnValue"].Value = txtColumnValue.Text;
sqlCmd.ExecuteNonQuery();
}
}
Of course you don't need the call to Parameters.Clear
Then there is a problem in the way in which you pass the paramenters to the sp_executesql call inside the stored procedure. That system storedprocedure requires that you set the datatype for every parameter used in the query and an initialization list of these parameters.
You should write
...
-- Insert statements for procedure here
declare #Query nvarchar(4000)
declare #ParmDefinition nvarchar(500);
set #Query = 'INSERT into Registrant(DateCreated,EventId,FormId,'+
(#ColumnName) +') values (CURRENT_TIMESTAMP, #EventId, #FormId, #ColumnValue)'
set #ParmDefinition = N'#ColumnValue varchar(100), #EventID int, #FormID int'
exec sp_executesql #Query, #ParmDefinition,
#ColumnValue = #ColumnValue,
#EventID = #EventID,
#FormID = #FormID
You are clearing the parameters:
sqlCmd.Parameters.Clear();
You need to add them over and over:
foreach (RepeaterItem rpItem in RepeaterForm.Items)
{
Label lblDisplayName = rpItem.FindControl("lblDisplayName") as Label;
Label lblColumnName = rpItem.FindControl("lblColumnName") as Label;
TextBox txtColumnValue = rpItem.FindControl("txtColumnValue") as TextBox;
if (txtColumnValue != null)
{
sqlCmd.Connection = sqlConn;
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.CommandText = "spInsFormRegistrant";
sqlCmd.Parameters.Clear(); //that's fine, keep it
//just put them in here
sqlCmd.Parameters.Add("#EventId", SqlDbType.Int).Value = eventId;
sqlCmd.Parameters.Add("#FormId", SqlDbType.Int).Value = formId;
sqlCmd.Parameters.Add("#ColumnName", SqlDbType.NVarChar).Value = lblColumnName.Text;
sqlCmd.Parameters.Add("#ColumnValue", SqlDbType.NVarChar).Value = txtColumnValue.Text;
sqlCmd.ExecuteNonQuery();
}
}
Related
I've got the following method that is supposed to delete the Holiday names from the database given from the List's that are passed in as arguments. The problem I am having is it isn't deleting anything from the database. Here is part of the method that I am having issues with:
private void RemoveGloOrderDays(List<SessionInfoList> sessionList, List<Holiday> selectedOrderHolidays, List<Holiday> selectedHolidays, List<string> orderDays, List<string> noOrderDays)
{
try
{
using (SqlCommand cmd = new SqlCommand())
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
cmd.CommandTimeout = 600;
cmd.CommandText = "[dbo].[RemoveGlobalOrderDays]";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = connection;
cmd.Parameters.Add("#SessionId", SqlDbType.Int);
cmd.Parameters.Add("#SelectedOrderHolidays", SqlDbType.NVarChar);
cmd.Parameters.Add("#SelectedHolidays", SqlDbType.NVarChar);
cmd.Parameters.Add("#OrderDays", SqlDbType.NVarChar);
cmd.Parameters.Add("#NoOrderDays", SqlDbType.NVarChar);
connection.Open();
foreach (SessionInfoList session in sessionList)
{
cmd.Parameters["#SessionId"].Value = session.SessionID;
cmd.Parameters["#SelectedOrderHolidays"].Value = DBNull.Value;
string joinedNames = string.Join(",", selectedOrderHolidays.Select(h => h.Name.Trim()));
if (!string.IsNullOrEmpty(joinedNames))
{
cmd.Parameters["#SelectedOrderHolidays"].Value = joinedNames;
}
cmd.Parameters["#SelectedHolidays"].Value = DBNull.Value;
joinedNames = string.Join(",", selectedHolidays.Select(h => h.Name.Trim()));
if (!string.IsNullOrEmpty(joinedNames))
{
cmd.Parameters["#SelectedHolidays"].Value = joinedNames;
}
Here is my stored procedure:
IF OBJECT_ID('[dbo].[RemoveGlobalOrderDays]') IS NOT NULL
DROP PROCEDURE [dbo].[RemoveGlobalOrderDays]
GO
CREATE PROCEDURE [dbo].[RemoveGlobalOrderDays]
#SessionId int,
#SelectedHolidays nvarchar(500),
#SelectedOrderHolidays nvarchar(500),
#OrderDays nvarchar(500),
#NoOrderDays nvarchar(500)
WITH ENCRYPTION
AS
BEGIN
SET NOCOUNT ON;
UPDATE [cfgSchedule]
SET
[OrderDays] = #OrderDays,
[NoOrderDays] = #NoOrderDays
WHERE [cfgSchedule].[SessionId] = #SessionID
DELETE FROM [SessionHolidayMapping]
WHERE [HolidayName] = #SelectedHolidays
AND
[SessionId] = #SessionId
DELETE FROM [SessionOrderHolidayMapping]
WHERE [SessionId] = #SessionId
AND
[HolidayName] = #SelectedOrderHolidays
END
GO
As far as I can see you are passing list of names separated by comma and you want to delete all those names. You need to use IN operator to find all holiday names that should be deleted.
Here is an example how to do it for #SelectedHolidays:
declare #SelectedHolidays nvarchar(500) = 'H1,H2,H3'
declare #SelectedHolidaysXml xml = cast(replace(N'<R><I>' + #SelectedHolidays + N'</I></R>', ',', '</I><I>') as xml)
DELETE FROM [SessionHolidayMapping]
WHERE [HolidayName] in (select x.items.value('(.)[1]', 'NVARCHAR(500)') from #SelectedHolidaysXml.nodes('/R/I') as x(items))
AND [SessionId] = #SessionId
It is ugly, but I don't know of better way to split comma separated values in sql server.
Instead of using nvarchar, you could use table valued parameters for the parameters #Selectedholidays and #selectedorderholidays and then something like
DELETE [SessionHolidayMapping] FROM [SessionHolidayMapping] A
Inner join #selectedholidays S
On A.[HolidayName] = S.Holidayname where A.[SessionId] = #SessionId.
The "HolidayName" is one column of the parameter.
I'm on my phone and cannot test it appropriately.
I apologise for this formatting. I am new to programming and new to this site, so I will try and make the question as clear as possible.
I have a webform for accessing/modifying a Customer database. I have a button for entering new customers details which will automatically assign an ID number by getting the highest ID number from the database, and incrementing by one (and posting to form textbox).
This is the code I have written:
protected void btnNew_Click(object sender, EventArgs e)
{
Clear();
command.Connection = conn;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "NewCustomer";
conn.Open();
SqlParameter maxid = new SqlParameter();
maxid.ParameterName = "#MaxID";
maxid.SqlDbType = SqlDbType.Int;
maxid.Direction = ParameterDirection.Output;
command.Parameters.Add(maxid);
command.ExecuteNonQuery();
NewCustId = Convert.ToInt32(maxid.Value);
NewCustId += 1;
txtCustID.Text = (NewCustId).ToString();
txtCustID.DataBind();
conn.Close();
}
This is the stored procedure:
CREATE PROCEDURE NewCustomer
(#MaxID INT OUTPUT)
AS
BEGIN
SELECT #MaxID = MAX(CustID)
FROM dbo.Customer
END
I have tried many different ways of coding it, but nothing seems to work.
The code I have posted has an exception at ExecuteNonQuery saying arguments were supplied and procedure has no parameters. When I place command.Parameters.Add(maxid); underneath ExecuteNonQuery, it returns a 1.
I ran the SQL Query alone to see what would happen and it returns a correct answer in an unnamed cell. For some reason the Column Name disappears when it comes up. Then when I try to use the C# code to access the unnamed cell, I can't seem to access it because the column 'CustID' "doesn't exist".
With this code, I know that the SQL command is executing, and then the C# code increments by 1, but it seems that the return value I am getting is 0.
I appreciated any ideas that I can get on how to fix this. Thank you.
Edit: I have also tried:
DataTable table = new DataTable();
adapter.Fill(table);
NewCustId = table.Rows[0].Field("CustID");
(This is where it said 'CustID' column didn't exist)
Change your code to the following and try again:
Clear();
command.Connection = conn;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "NewCustomer";
conn.Open();
NewCustId = Convert.ToInt32(cmd.ExecuteScalar().ToString());
NewCustId += 1;
txtCustID.Text = NewCustId.ToString();
conn.Close();
And your stored procedure is:
CREATE PROCEDURE NewCustomer
(
)
AS
BEGIN
SELECT MAX(CustID)
FROM dbo.Customer;
END
ExecuteNonQuery() expects no results. Try ExecuteReader() instead.
I second what marc_S is saying about this running into issues.
Since you are using max ID and incrementing by 1 to insert a new record in the database, I suggest that you use Identity(seed, increment_value) for this column.
That way you don't have to find max to insert a new record and you avoid lots of transaction issues.
Once the transaction is done
Possible Design:
Create Table Customer
(
Id Int Identity(1,1),
Name varchar(50)
)
Create Proc NewCustomer
(
#Name varchar(50)
)
As
(
DECLARE #custID Int
SET NOCOUNT ON
INSERT INTO Customer (Name) Values('Your Name')
SET #custID = SCOPE_IDENTITY()
RETURN #custID
)
protected void btnNew_Click(object sender, EventArgs e)
{
Clear();
command.Connection = conn;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "NewCustomer";
conn.Open();
SqlParameter name = new SqlParameter();
name.ParameterName = "#Name";
name.Direction = ParameterDirection.Input;
name.SqlDbType = SqlDbType.Varchar;
name.Value = "Your Name";
command.Parameters.Add(name);
SqlParameter returnValue= new SqlParameter();
returnValue.ParameterName = "#custID";
returnValue.SqlDbType = SqlDbType.Int;
returnValue.Direction = ParameterDirection.ReturnValue;
command.Parameters.Add(maxid);
command.ExecuteNonQuery();
NewCustId = Convert.ToInt32(returnValue.Value);
txtCustID.Text = (NewCustId).ToString();
txtCustID.DataBind();
conn.Close();
}
I am trying to write a code do payment and update the status as well. In the following code I have done the logic to submit the payment which is working correctly but I am not able to update the status. Status is a column in Item_Order table which must get update after do the payment
My code is :
delegate void PaymentDone();
public void paySave()
{
SqlConnection conn1 = new SqlConnection();
try
{
conn1.ConnectionString = "
server=.\\ms2k5;database=Info_Connect;Trusted_Connection=true";
conn1.Open();
SqlCommand insertPayment = new SqlCommand("Delegate_SP", conn1);
insertPayment.CommandType = CommandType.StoredProcedure;
string currentDate = DateTime.Today.ToString();
if (Convert.ToDateTime(payDate.Text) >= Convert.ToDateTime(currentDate))
{
insertPayment.Parameters.Add("#reciptId", SqlDbType.VarChar);
insertPayment.Parameters["#reciptId"].Value = fullfill.Text;
insertPayment.Parameters.Add("#payDate", SqlDbType.DateTime);
insertPayment.Parameters["#payDate"].Value =
Convert.ToDateTime(payDate.Text);
insertPayment.Parameters.Add("#balPay", SqlDbType.Float);
insertPayment.Parameters["#balPay"].Value = Convert.ToDouble(balace.Text) - Convert.ToDouble(amnt1.Text);
insertPayment.Parameters.Add("#payDone", SqlDbType.Float);
insertPayment.Parameters["#payDone"].Value =
Convert.ToDouble(amnt1.Text);
insertPayment.Parameters.Add("#fullfillID_FK", SqlDbType.VarChar);
insertPayment.Parameters["#fullfillID_FK"].Value = fullfill.Text;
insertPayment.Parameters.Add("#clintID_FK", SqlDbType.Int);
insertPayment.Parameters["#clintID_FK"].Value =
(clintId_FK.Text).ToString();
insertPayment.Parameters.Add("#operation", SqlDbType.VarChar);
insertPayment.Parameters["#operation"].Value = 3;
insertPayment.ExecuteNonQuery();
}
else
{
MessageBox.Show("Payment Date Should be later than Full Order Date");
}
}
}
public void payUpdate()
{
SqlConnection conn1 = new SqlConnection();
try
{
conn1.ConnectionString = "
server=.\\ms2k5;database=Info_Connect;Trusted_Connection=true";
conn1.Open();
SqlCommand insertStaus = new SqlCommand("Delegate_SP", conn1);
insertStaus.CommandType = CommandType.StoredProcedure;
insertStaus.Parameters.Add("#status", SqlDbType.VarChar);
insertStaus.Parameters["#status"].Value = "RUNING";
if (balace.Text.Equals("0"))
{
insertStaus.Parameters.Add("#status", SqlDbType.VarChar);
insertStaus.Parameters["#status"].Value = "CLOSE";
}
else
{
insertStaus.Parameters.Add("#status", SqlDbType.VarChar);
insertStaus.Parameters["#status"].Value = "RUNING";
}
MessageBox.Show("3");
insertStaus.Parameters.Add("#operation", SqlDbType.VarChar);
insertStaus.Parameters["#operation"].Value = 2;
insertStaus.ExecuteNonQuery();
}
}
And my stored procedure is
ALTER PROCEDURE [dbo].[Delegate_SP]
#reciptId varchar(50)=null,
#balPay float,
#payDone float=null,
#payDate datetime=null,
#fullfillId_FK varchar(50)=null,
#clintId_FK int=null,
#status varchar(50)=null,
#operation int,
#fullfillId varchar(50)=null
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
if #operation=3
BEGIN
UPDATE Recipt set balPay=#balPay where reciptId=#reciptId
if ##rowcount=0
insert into Recipt(reciptId,balPay,payDone,payDate,fullfillId_FK,clintId_FK)values
(#reciptId,#balPay,#payDone,#payDate,#fullfillId_FK,#clintId_FK)
update Item_Full set totCost=(select balPay from Recipt) where fullfillId=#reciptId
END
if #operation=2
BEGIN
UPDATE Item_Order set status=#status where orderId=#reciptId
END
END
the problem is that I got tdsparser exception in payUpdate method... the paySave method is working correctly
ALTER PROCEDURE dbo.SP_InsertTicket
/*
(
#parameter1 int = 5,
#parameter2 datatype OUTPUT
)
declare #i as numeric
exec SP_InsertTicket 'asd','cd#y.com','232323','dasasd','sdasdas','01-jan-2010',#i output,'sdas','sdasd','02-jan-2010'
select #i*/
#Client_FullName varchar(30),
#Client_EmailAdd varchar(50),
#Client_Telephn varchar(15),
#Ticket_Subject varchar(50),
#Ticket_Source varchar(15),
#Ticket_CreateDate Datetime,
#Ticket_Id integer output,
#Que_Message varchar(100),
#Que_Attachment varchar(max),
#Que_UpdateDate Datetime
AS
declare #TickID integer;
/* SET NOCOUNT ON */
BEGIN
INSERT INTO tbl_Ticket (Client_FullName,Client_EmailAdd,Client_Telephn,Ticket_Subject,Ticket_Source,Ticket_CreateDate)
VALUES (#Client_FullName, #Client_EmailAdd ,#Client_Telephn,#Ticket_Subject,#Ticket_Source,#Ticket_CreateDate)
Select #TickID = MAX(Ticket_Id) from tbl_Ticket
set #Ticket_Id=#TickID
INSERT INTO tbl_TicketQuestion (Ticket_Id,Que_Message,Que_Attachment,Que_UpdateDate)
VALUES (#TickID,#Que_Message,#Que_Attachment,#Que_UpdateDate)
END
RETURN
This is my store procedure in which i need to return Ticket_Id to send it via email app
It insert records well bt not able to retirn value in DAL
Below is the code for executing stored procedure which returns value
public class cls_DAL
{
public cls_DAL()
{
//
// TODO: Add constructor logic here
//
}
static string strConn = System.Configuration.ConfigurationManager.ConnectionStrings["conString"].ConnectionString.ToString();
SqlConnection con = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
DataSet ds = new DataSet();
DataTable dt = new DataTable();
public int insert_NewTicket(string fullname, string emailadd, string telephone, string subject, string source, DateTime date,string Message, string attachment, DateTime updatedate)
{
try
{
con.Open();
cmd = new SqlCommand("SP_InsertTicket", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Client_FullName", fullname);
cmd.Parameters.AddWithValue("#Client_EmailAdd", emailadd);
cmd.Parameters.AddWithValue("#Client_Telephn",telephone);
cmd.Parameters.AddWithValue("#Ticket_Subject", subject);
cmd.Parameters.AddWithValue("#Ticket_Source",source);
cmd.Parameters.AddWithValue("#Ticket_CreateDate",date);
cmd.Parameters.AddWithValue("#Ticket_Id",0);
cmd.Parameters.AddWithValue("#Que_Message", Message);
cmd.Parameters.AddWithValue("#Que_Attachment", attachment);
cmd.Parameters.AddWithValue("#Que_UpdateDate",updatedate);
cmd.Parameters["#Ticket_Id"].Direction = ParameterDirection.InputOutput;
return cmd.ExecuteNonQuery();
int i = (int)cmd.Parameters["#Ticket_Id"].Value;
}
catch
{
throw;
}
finally
{
cmd.Dispose();
con.Close();
con.Dispose();
}
}
}
Its just a guess, not sure. You can give a try the following:
cmd.Parameters["#Ticket_Id"].Direction = ParameterDirection.InputOutput;
TO
cmd.Parameters["#Ticket_Id"].Direction = ParameterDirection.Output;
That won't compile you'll get unreachable code
cmd.Parameters["#Ticket_Id"].Direction = ParameterDirection.InputOutput; cmd.ExecuteNonQuery();
return (int)cmd.Parameters["#Ticket_Id"].Value;
or #Matt's solution below...
That cast is iffy as well...
And in a multi user scenario, ticketid will race.
Think about what could (will!!!) happen if you run two of these at the same time
Should be wrapped in a transaction.
And you don't need Max, either, Use Scope_Identity
You could run Select Scope_Identity() after the Insert statement. Then in your DAL Method return Convert.ToInt32(cmd.ExecuteScalar())
Change this:
return cmd.ExecuteNonQuery();
to
Int i = cmd.ExecuteScalar();
If you are only returning one integer from that procedure.
ExecuteNonQuery() isnt the method you want to be using here
How can I use a stored procedure (with parameters - has a return value of type int) from code behind?
My stored procedure looks like this :
ALTER Procedure [dbo].[sp_Noskheh_SumOfTotalPay]
#Co_ID int
AS
-----------------
Declare #Sum bigint
-----------------
BEGIN
SELECT
#Sum = SUM(TotalPay)
FROM Noskheh
WHERE
(Co_ID = #Co_ID)
RETURN #Sum
END
I want to use #Sum in code behind ...
Would you please show me a way for doing that ?
Thanks in advance
best regards
You need to set up a SqlConnection and a SqlCommand. If you have your code with the RETURN #Sum statement in the end, you need to do this (define a parameter of type RETURN_VALUE):
using(SqlConnection _conn = new SqlConnection(-your-connection-string-here))
using(SqlCommand _cmd = new SqlCommand("dbo.sp_Noskheh_SumOfTotalPay", _conn))
{
_cmd.CommandType = CommandType.StoredProcedure;
_cmd.Parameters.Add(new SqlParameter("#CO_ID", SqlDbType.Int));
_cmd.Parameters["#CO_ID"].Value = 5; // whatever value you want
_cmd.Parameters.Add(new SqlParameter("#RETURN_VALUE", SqlDbType.BigInt));
_cmd.Parameters["#RETURN_VALUE"].Direction = ParameterDirection.ReturnValue;
_conn.Open();
_cmd.ExecuteNonQuery();
Int64 result = Int64.Parse(_cmd.Parameters["#RETURN_VALUE"].Value);
_conn.Close();
}
It would be a lot easier if you would replace that RETURN statement with a simple SELECT:
SELECT #Sum
In that case, you can use the simplified version I had before - using .ExecuteScalar() to retrieve the single value of the single row being returned from the stored proc:
using(SqlConnection _conn = new SqlConnection(-your-connection-string-here))
using(SqlCommand _cmd = new SqlCommand("dbo.sp_Noskheh_SumOfTotalPay", _conn))
{
_cmd.CommandType = CommandType.StoredProcedure;
_cmd.Parameters.Add(new SqlParameter("#CO_ID", SqlDbType.Int));
_cmd.Parameters["#CO_ID"].Value = 5; // whatever value you want
_conn.Open();
object result = _cmd.ExecuteScalar();
_conn.Close();
Int64 sum = Int64.Parse(result);
}
That should call your stored proc, read the single value you're returning, and converting it into an int variable called sum.
There is no shortage of tutorials on this subject.
You can add an SqlParameter #Sum with Direction set to ReturnValue
Example:
SqlCommand cmd = new SqlCommand():
cmd.Connection = // place your SqlConnection object;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "StoreProcedureName";
cmd.Parameters.Add("#Sum", SqlDbType.BigInt).Direction = ParameterDirection.ReturnValue