executenonquery not working in for loop - c#

In database:
Alter Procedure Update_MaterialTransactionsto2ForWithdrawal
#materialName varchar(50),
#staffNumber varchar(10),
#description varchar(50),
#transactionID int
As
Begin
Update Table_MaterialTransactions
set Status=2
where StaffNumber = #staffNumber
and CrossSection = #description
and SubSubCategory = #materialName
and Status = 1
and TransactionID = #transactionID
End
In data access layer:
public static void UpdateMaterial(string staffNumber,string materialName,string description,int transaction)
{
SqlConnection connection = new SqlConnection(ConnectDatabase.ReturnConnectionString());
//I am passing connection string as the parameter
try
{
connection.Open();
SqlCommand cmd = new SqlCommand("Update_MaterialTransactionsto2ForWithdrawal", connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Clear();
cmd.Parameters.Add("#materialName", SqlDbType.Varchar, 50).Value = materialName;
cmd.Parameters.Add("#staffNumber", SqlDbType.Varchar, 50).Value = staffNumber;
cmd.Parameters.Add("#description", SqlDbType.Varchar, 50).Value = description;
cmd.Parameters.Add("#transactionID", SqlDbTypeInt).Value = transactionID;
int i = cmd.ExecuteNonQuery();
connection.Close();
}
catch(Exception ex)
{
connection.Close();
}
On the client side:
void btnSubmit_Click(Object sender,EventArgs e)
{
int j=0,k=0;
for(int i=0;i<transactions.Count;i++)
{
string id = "ctl00$ContentPlaceHolder1$" + i.ToString();
CheckBox chk=(CheckBox)Page.FindControl(id);
if(chk.Checked == true)
{
Objects.UpdateMaterial(staffNumbers[i].ToString(), materials[i].ToString(), descriptions[i].ToString(), Convert.ToInt32(transactions[i]));
j++;
}
else
{
Objects.DeleteTheSelectedRowOfMaterialTransaction(staffNumbers[i].ToString(), materials[i].ToString(), descriptions[i].ToString(), Convert.ToInt32(transactions[i]));
k++;
}
}
I have check boxes in the table and when the user checks the check boxes and clicks submit, the boxes which are checked will update the database.
But the cmd.ExecuteNonQuery() is not executing and it is returning 0 rows. It is not throwing any error. But if I do this manually in the database, the stored procedure is working fine.
Kindly tell me where I am going wrong.

try adding last line in procedure
Return ##Rowcount

Related

Convert Command.ExecuteScalar() To Int

I need to insert a line in my question table and retrieve the inserted id. I initialize my sql command and execute it with ExecuteScalar(). I'm trying to convert the result of this method to int but I can not do it.
I tried to do that:
int result = Convert.ToInt32(Command.ExecuteScalar));
or
int result = (int)Command.ExecuteScalar();
but nothing work
here is my function
public int AddQuestionOrientation(Question questionForAdd)
{
try
{
con = new SqlConnection(connectionString);
con.Open();
SqlCommand command;
String sql = "";
sql = "INSERT INTO QUESTION VALUES(#Libelle,
#Bareme,2,#Filliere)";
SqlParameter param = new SqlParameter();
param.ParameterName = "#Libelle";
param.Value = questionForAdd.Libelle;
SqlParameter param2 = new SqlParameter();
param2.ParameterName = "#Bareme";
param2.Value = questionForAdd.Bareme;
SqlParameter param3 = new SqlParameter();
param3.ParameterName = "#Filliere";
param3.Value = questionForAdd.IdFiliere;
command = new SqlCommand(sql, con);
command.Parameters.Add(param);
command.Parameters.Add(param2);
command.Parameters.Add(param3);
int idQuestionInserted = (int)command.ExecuteScalar();
command.Dispose();
con.Close();
return idQuestionInserted;
}
catch(Exception ex)
{
return 0;
}
}
If I try with the cast (int), I have the message error:
Object reference not set to an instance of an object
If I try with the Convert.ToInt32, my variable "IdQuestionInserted" is equal to 0.
This is a big departure from where you started. But you have several issue going on there. You should use the USING statement around objects with the IDisposable interface (connections, commands, etc...).
This code is all untested but should be really close.
Start with creating a stored procedure so you can start creating layers in your application.
create Procedure Question_Insert
(
#Libelle varchar(50)
, #Bareme varchar(50)
, #Filliere varchar(50)
, #QuestionID int output
) as
set nocount on;
INSERT INTO QUESTION
(
Libelle
, Bareme
, Filliere
)
values
(
#Libelle
, #Bareme
, #Filliere
)
select #QuestionID = SCOPE_IDENTITY()
Then in your dotnet code you need to change up a few things to make it cleaner and more robust. Ideally you should do something better than simply return 0 when there is an error. It will be really tough to debug when something goes wrong if you simply return a 0. This is like an error message that says, "An error occurred". Pretty useless. Do something with the error. Capture the message to enable you to fix it.
public int AddQuestionOrientation(Question questionForAdd)
{
try
{
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
using (SqlCommand command = new SqlCommand("Question_Insert"))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("#Libelle", SqlDbType.VarChar, 50).Value = questionForAdd.Libelle;
command.Parameters.Add("#Bareme", SqlDbType.VarChar, 50).Value = questionForAdd.Bareme;
command.Parameters.Add("#Filliere", SqlDbType.VarChar, 50).Value = questionForAdd.IdFiliere;
command.Parameters.Add("#QuestionID", SqlDbType.Int).Direction = ParameterDirection.Output;
command.ExecuteNonQuery();
return int.Parse(command.Parameters["#QuestionID"].Value.ToString());
}
}
}
catch (Exception ex)
{
return 0;
}
}
To get inserted id use SCOPE_IDENTITY() add SELECT CAST(scope_identity() AS int to command query to do
INSERT INTO QUESTION
VALUES(#Libelle, #Bareme, 2, #Filliere);
SELECT CAST(scope_identity() AS int;
this query will return inserted id for you.

SQL Server stored procedure insert query

In my C# code I am using :
public void Add(int ID)
{
foreach (AccessoireToSell item in OrderToAdd.Accessoires)
{
Adder(item.Ref, item.Qte, item.SellPrice, ID);
}
}
private void Adder(int refid,int Qtetosell,string sellprice,int ID)
{
SqlParameter[] param = new SqlParameter[4];
param[0] = new SqlParameter("#AccessoireID", SqlDbType.Int);
param[0].Value = refid;
param[1] = new SqlParameter("#Qte", SqlDbType.Int);
param[1].Value = Qtetosell;
param[2] = new SqlParameter("#Price", SqlDbType.VarChar, 50);
param[2].Value = sellprice;
param[3] = new SqlParameter("#ORDERID", SqlDbType.Int);
param[3].Value = ID;
Function.Execute(param, "AccessoiresAddOrder");
}
The procedure AccessoiresAddOrder :
ALTER PROCEDURE [dbo].[AccessoiresAddOrder]
#ORDERID int,
#AccessoireID int,
#Qte int,
#Price Varchar(50)
AS
INSERT INTO [dbo].[Accessoires_OrderDetails] ([orderID], [AccessoireID],[Qte], [Price])
VALUES (#ORDERID, #AccessoireID, #Qte, #Price)
I don't understand why the records get inserted 2 times in a row. For example I insert a row from the Datagridview and I get the same row twice in my SQL Server table.
Please note that I checked the AccessoireToSell list counts during the execution as well it say for "Count = 2" in my table I find 4 records.
Execute method :
public void Execute(SqlParameter[] param, string ProcName)
{
SqlCommand Cmd = new SqlCommand();
Cmd.CommandText = ProcName;
Cmd.CommandType = CommandType.StoredProcedure;
if (param != null)
{
Cmd.Parameters.AddRange(param);
}
Cmd.Connection = Base.Connection;
if (Base.Status() == true)
Cmd.ExecuteNonQuery();
else
Base.Open();
Cmd.ExecuteNonQuery();
}
Use this code:-
if (Base.Status() == true)
Cmd.ExecuteNonQuery();
else
{
Base.Open();
Cmd.ExecuteNonQuery();
}
The difference is just add curly braces {....} to the else clause. The code without curly braces {} is executing the Cmd.ExecuteNonQuery() call twice.

SQL Output Parameter

I have a questionnaire which stores answers for each user who does the test. I need to store the output in the database (which is the user doing the test.) I'm not quite sure what i am doing wrong. Currently my inputID returns 0. (InputAnswers inputs the test answers for that user to database)
CREATE PROCEDURE [dbo].[InputAnswers]
#QuestionID int,
#InputID int OUTPUT,
#Answer nchar,
#Remark nvarchar(50)
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO Answers (InputID, QuestionID, Answer, Remark) VALUES (#InputID, #QuestionID, #Answer, #Remark)
END
The code below loads the answers from the list view which holds the questions:
private void LoadAnswers(int inputID)
{
foreach (StepControl step in dckSteps.Children)
{
foreach (QuestionControl quest in step.listQuestions.Items)
{
int questionID = quest.questionID;
string answer = quest.answer;
string remark = quest.txtRemark.Text;
SqlConnection conDatabase = new SqlConnection(String.Format(#"Data Source={0};Initial Catalog={1};Persist Security Info=True;User ID={2};Password={3}", SQLSERVER_ID, SQLDatabaseName, SQLServerLoginName, SQLServerPassword));
string query = "InputAnswers";
SqlCommand cmd = new SqlCommand(query, conDatabase);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#InputID", SqlDbType.Int).Value = inputID;
cmd.Parameters.Add("#QuestionID", SqlDbType.Int).Value = questionID;
cmd.Parameters.Add("#Answer", SqlDbType.NChar).Value = answer;
cmd.Parameters.Add("#Remark", SqlDbType.NVarChar).Value = remark;
conDatabase.Open();
cmd.ExecuteNonQuery();
conDatabase.Close();
}
}
}
I then load these answers into the button click method:
private void btnSubmit_Click(object sender, RoutedEventArgs e)
{
string name = txtName.Text;
string cno = txtCNO.Text;
var date = datePicker.SelectedDate;
int inputID = 0;
SqlConnection conDatabase = new SqlConnection(String.Format(#"Data Source={0};Initial Catalog={1};Persist Security Info=True;User ID={2};Password={3}", SQLSERVER_ID, SQLDatabaseName, SQLServerLoginName, SQLServerPassword));
string query = "SaveInput";
SqlCommand cmd = new SqlCommand(query, conDatabase);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#InputID", SqlDbType.Int).Value = ParameterDirection.Output;
cmd.Parameters.Add("#Name", SqlDbType.NVarChar).Value = name;
cmd.Parameters.Add("#CNO", SqlDbType.NVarChar).Value = cno;
cmd.Parameters.Add("#Date", SqlDbType.DateTime).Value = date;
conDatabase.Open();
cmd.ExecuteNonQuery();
conDatabase.Close();
LoadAnswers(inputID);
}
This all works correctly apart from sending the OUTPUT back to the database. Any ideas?
EDIT: The procedure SaveInput looks like this: (SaveInput stores the user info)
CREATE PROCEDURE [dbo].[SaveInput]
#InputID int OUTPUT,
#Name nvarchar(50),
#CNO nvarchar(50),
#Date DATETIME
AS
BEGIN
SET NOCOUNT ON;
IF(#InputID = 0)
BEGIN
INSERT INTO Input (Name, CNO, Date) VALUES (#Name, #CNO, #Date)
SET #InputID = ##IDENTITY
END
ELSE
BEGIN
UPDATE Input SET Name = #Name,
CNO = #CNO,
Date = #Date
WHERE InputID = #InputID
END
END
I have a feeling i don't need to use OUTPUT on both procedures.
This is at least part of the problem:
cmd.Parameters.Add("#InputID", SqlDbType.Int).Value = ParameterDirection.Output;
That's creating an input parameter - but giving it a value which is the enum value ParameterDirection.Output. You want:
cmd.Parameters.Add("#InputID", SqlDbType.Int).Direction = ParameterDirection.Output;
You then need to fetch the result from the parameter after executing the command:
cmd.ExecuteNonQuery();
// You might want to store the parameter reference in a local variable instead
// of fetching it again afterwards.
int inputId = (int) cmd.Parameters["#InputID"].Value;
If you want the parameter to be input/output though, you should be using ParameterDirection.InputOutput (and giving it a value before executing the command). For example:
int inputId = ...;
var inputIdParameter = cmd.Parameters.Add("#InputID", SqlDbType.Int);
inputIdParameter.Direction = ParameterDirection.InputOutput;
inputIdParameter.Value = inputId;
...
cmd.ExecuteNonQuery();
inputId = (int) inputIdParameter.Value;

Can't delete User from table through windows form [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am having problem deleting user from table. I can insert the data from form to table but while deleting it only gives else statement result as "SOME ERRORS OCCURRED WHILE PROCESSING THE REQUEST". StaffID is auto increment. Please help.
Delete Button :
private void btnDeleteUser_Click(object sender, EventArgs e)
{
try
{
int result = uc.ManageUser(txtFullName.Text, txtAddress.Text, txtPhone.Text, txtEmail.Text, Convert.ToDateTime(dateTimePickerJoinedDate.Text), txtUserame.Text, txtPassword.Text, Convert.ToDateTime(dateTimePickerCreatedDate.Text), "D");
if (result == 1)
{
MessageBox.Show("User Deleted");
dgvUserDetails.DataSource = uc.SelectAllUsers();
//MakeFieldsBlank();
}
else
{
MessageBox.Show("SOME ERRORS OCCURRED WHILE PROCESSING THE REQUEST");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
}
}
}
ManageUser Class
public int ManageUser(String Name, String Address, String Phone, String Email, DateTime JoinedDate, String Username, String Password, DateTime CreatedDate, String Mode)
{
try
{
int result = 0;
SqlCommand cmd = new SqlCommand("sp_ManageUser", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#StaffID",DBNull.Value);
cmd.Parameters.AddWithValue("#Name", Name);
cmd.Parameters.AddWithValue("#Address", Address);
cmd.Parameters.AddWithValue("#Phone", Phone);
cmd.Parameters.AddWithValue("#Email", Email);
cmd.Parameters.AddWithValue("#JoinedDate", JoinedDate);
cmd.Parameters.AddWithValue("#Username", Username);
cmd.Parameters.AddWithValue("#Password", Password);
cmd.Parameters.AddWithValue("#CreatedDate", CreatedDate);
//cmd.Parameters.AddWithValue("#IsActive", IsActive);
cmd.Parameters.AddWithValue("#Mode", Mode);
conn.Open();
result = cmd.ExecuteNonQuery();
conn.Close();
return result;
}
catch (Exception ex)
{
throw ex;
}
}
Procedure : sp_ManageUser
USE [db_ProjectStatusManager]
GO
/****** Object: StoredProcedure [dbo].[sp_ManageUser] Script Date: 12/05/2014 01:29:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
ALTER PROCEDURE [dbo].[sp_ManageUser]
-- Add the parameters for the stored procedure here
#StaffID int,
#Name nvarchar(100),
#Address nvarchar(500),
#Phone nvarchar(100),
#Email nvarchar(100),
#JoinedDate date,
#Username nvarchar(50),
#Password nvarchar(max),
#CreatedDate date,
#Mode varchar(1)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT OFF;
-- Insert statements for procedure here
if(#Mode='I')
insert into tbl_Staff (Name,Address,Phone,Email,JoinedDate,Username,Password,CreatedDate) values(#Name,#Address,#Phone,#Email,#JoinedDate,#Username,#Password,#CreatedDate)
if(#Mode='U')
Update tbl_Staff set Name=#Name,Address=#Address,Phone=#Phone,Email=#Email,JoinedDate=#JoinedDate,Username=#Username,Password=#Password,CreatedDate=#CreatedDate where StaffID=#StaffID
if(#Mode='D')
Delete from tbl_Staff where StaffID=#StaffID
end
Load Users To TextBox
private void FrmUsers_Load(object sender, EventArgs e)
{
UserClass uc = new UserClass();
dgvUserDetails.DataSource = uc.SelectAllUsers();
dgvUserDetails.AllowUserToAddRows = false;
dgvUserDetails.AllowUserToOrderColumns = false;
panel1.Enabled = false;
}
UserClass. SelectAllUsers
public DataTable SelectAllUsers()
{
try
{
SqlCommand cmd = new SqlCommand("Select * from tbl_Staff", conn);
DataTable dt = new DataTable();
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
dt.Load(dr);
conn.Close();
return dt;
}
catch (Exception ex)
{
throw ex;
}
}
You need to pass the value for the parameter #StaffID because the SP requires this parameter for the UPDATE and DELETE parts. It is only the INSERT part that doesn't require the #StaffID value
uc.ManageUser(txtStaffID.Text, txtFullName.Text, .......
....
public int ManageUser(string staffID, String Name, ......)
{
try
{
int result = 0;
SqlCommand cmd = new SqlCommand("sp_ManageUser", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#StaffID", Convert.ToInt32(staffID));
cmd.Parameters.AddWithValue("#Name", Name);
....
}
Of course this means that you need to save somewhere that value when you load your user data.
This could be a global variable or some textbox in readonly mode or hidden in your form or as a property of a User class. (This would a lot better. You could pass the whole instance of a User to your UserManager class instead of a lot of separated parameters)
Also pay attention to the datatype of the parameter #StaffID. The SP expects an integer not a string.
You are passing a NULL value in 'StaffID' column in command parameter but your store procedure has where condition with 'StaffID', first you need to Get the 'StaffID' and then pass the it.
you get the StaffID by simple query
Select StaffID from tbl_Staff where Name=#Name and Username = #Username ;
You can follow this code to get the Staffid
public int getstaffid()
{
int staffid = 0;
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
string query = " Select StaffID from tbl_Staff where Name=#Name and Username = #Username";
cmd.CommandText = query;
SqlParameter param = new SqlParameter("#Name", txtFullName.Text);
cmd.Parameters.Add(param);
SqlParameter param = new SqlParameter("#Username", txtUserame.Text);
cmd.Parameters.Add(param);
try
{
con.Open();
staffid= (Int32)cmd.ExecuteScalar();
return staffid;
}
catch (Exception ex)
{
throw;
}
}
And Now in ManagerUSer()
public int ManageUser(String Name, ......)
{
try
{
int Staffid = getstaffid();
int result = 0;
SqlCommand cmd = new SqlCommand("sp_ManageUser", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#StaffID",Staffid);
cmd.Parameters.AddWithValue("#Name", Name);
....
}
}

SQL values not sent to table (C#/ASP.NET)

I am trying to set up an page to replicate an ATM using C#, ASP.NET and MSSQL (MSSQLEXPRESS if that matters). One part of it is a "new user" page to "sign up" for the "service". The problem is that when I test the page, I get an error message I set up to detect invalid credit card numbers, regardless of the number input. I believe the problem is in either my click event code, my C# query code or in my stored procedure to the event. I think the solution for this is most likely a simple one, but perhaps a pair of fresh eyes will see the problem.
Any help or suggestions would be greatly appreciated.
Code for button click:
protected void btnSubmit_Click(object sender, EventArgs e)
{
string display;
long cardnum;
string strcard = Request.Params.Get("__CREDITCARD");
if (long.TryParse(strcard, out cardnum))
{
string first = Request.Params.Get("__FIRSTNAME");
string middle = Request.Params.Get("__MIDDLENAME");
string last = Request.Params.Get("__LASTNAME");
string email = Request.Params.Get("__EMAIL");
string address = Request.Params.Get("__ADDRESS");
string username = Request.Params.Get("__USERNAME");
string password = Request.Params.Get("__PASSWORD");
int retcode = SqlQueries.changeUserInfo(cardnum, username, password, first, middle, last, email, address, out display);
switch (retcode)
{
case 1:
display = "Credit card number can only contain digits";
Alert.show(Page, this.GetType(), "Input Error", display);
UserDetails.Username = username;
UserDetails.Password = password;
Response.Redirect("HomePage.aspx");
return;
case 0:
display = "Invalid credit card number";
break;
}
}
else
{
display = "Credit card number can only contain digits";
}
Alert.show(Page, this.GetType(), "Input Error", display);
}
Which uses the changeUserInfo method from my SqlQueries class:
public static int changeUserInfo(long cardNum, string username, string password, string strFirstName, string strMiddleName, string strLastName, string strEmail, string strAddress, out string strError)
{
//SQL connection
SqlConnection objConn = new SqlConnection(strconnectionSting);
objConn.Open();
int intReturnValue = -1;
strError = string.Empty;
//If connection is open
if (objConn != null && objConn.State == ConnectionState.Open)
{
//Call to stored procedure: qprtnum_UpdatePartNumber
SqlCommand cmd = new SqlCommand("updateUserInfo", objConn);
cmd.CommandType = CommandType.StoredProcedure;
try
{
cmd.Parameters.Add(new SqlParameter("#CardNum", SqlDbType.Decimal, 150));
cmd.Parameters["#CardNum"].Precision = 18;
cmd.Parameters["#CardNum"].Scale = 0;
cmd.Parameters["#CardNum"].Value = cardNum;
cmd.Parameters.Add(new SqlParameter("#Username", SqlDbType.NVarChar, 50));
cmd.Parameters["#Username"].Value = username;
cmd.Parameters.Add(new SqlParameter("#Password", SqlDbType.NVarChar, 50));
cmd.Parameters["#Password"].Value = password;
cmd.Parameters.Add(new SqlParameter("#FirstName", SqlDbType.NVarChar, 150));
cmd.Parameters["#FirstName"].Value = strFirstName;
cmd.Parameters.Add(new SqlParameter("#MiddleName", SqlDbType.NVarChar, 150));
cmd.Parameters["#MiddleName"].Value = strMiddleName;
cmd.Parameters.Add(new SqlParameter("#LastName", SqlDbType.NVarChar, 150));
cmd.Parameters["#LastName"].Value = strLastName;
cmd.Parameters.Add(new SqlParameter("#EmailAddress", SqlDbType.NVarChar, 50));
cmd.Parameters["#EmailAddress"].Value = strEmail;
cmd.Parameters.Add(new SqlParameter("#Address", SqlDbType.NVarChar, 150));
cmd.Parameters["#Address"].Value = strEmail;
//Return Value
cmd.Parameters.Add("#ReturnValue", SqlDbType.Int);
cmd.Parameters["#ReturnValue"].Direction = ParameterDirection.ReturnValue;
cmd.ExecuteNonQuery();
intReturnValue = (int)cmd.Parameters["#ReturnValue"].Value;
strError = string.Empty;
}
catch (SqlException err)
{
intReturnValue = -1;
strError = err.Message;
}
catch (Exception ex)
{
intReturnValue = -1;
strError = ex.Message;
}
finally
{
objConn.Close();
}
}
else
{
//Error
intReturnValue = -1;
strError = "Error";
}
return intReturnValue;
}
Stored procedure "updateUserInfo":
USE [ATM]
GO
/****** Object: StoredProcedure [dbo].[updateUserInfo] Script Date: 4/15/2014 1:43:28 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
ALTER PROCEDURE [dbo].[updateUserInfo]
#CardNum AS decimal,
#Username AS nvarchar(50),
#Password AS nvarchar(50),
#FirstName AS nvarchar(150),
#MiddleName AS nvarchar(150),
#LastName AS nvarchar(150),
#EmailAddress nvarchar(50),
#Address nvarchar(150)
AS
BEGIN TRY
BEGIN TRANSACTION
DECLARE #ReturnValue AS INT;
--Set current date
DECLARE #Date AS numeric(18,0);
DECLARE #Hours int;
DECLARE #Minutes int;
DECLARE #Seconds int;
DECLARE #Milliseconds INT;
DECLARE #CurDate as VARCHAR(50);
SET #Hours = DATEPART(hh, GETDATE())
SET #Minutes = DATEPART(mi, GETDATE())
SET #Seconds = DATEPART(ss, GETDATE())
SELECT #CurDate = CONVERT(VARCHAR(35),GETDATE(),112)
SET #CurDate = #CurDate + CONVERT(VARCHAR(5), #Hours) + CONVERT(VARCHAR(5), #Minutes) + CONVERT(VARCHAR(5),#Seconds)
SELECT #Date = CONVERT(decimal(18,0), #CurDate)
-- Insert statements for procedure here
enter code here
UPDATE dbo.tblClient
SET [cliCardNum] = #CardNum
,[cliFirstName] = #FirstName
,[cliMiddleName] = #MiddleName
,[cliLastName] = #LastName
,[cliEmailaddress] = #EmailAddress
,[cliAddress] = #Address
,[TimeStamp] = #Date
,Enabled = 1
WHERE cliUsername=#Username AND cliPassword=#Password
SET #ReturnValue=0;
COMMIT TRANSACTION;
RETURN #ReturnValue
END TRY
BEGIN CATCH
IF ##TRANCOUNT > 0
ROLLBACK
-- Raise an error with the details of the exception
DECLARE #ErrMsg nvarchar(4000), #ErrSeverity int
SELECT #ErrMsg = ERROR_MESSAGE(),
#ErrSeverity = ERROR_SEVERITY()
RAISERROR(#ErrMsg, #ErrSeverity, 1)
SET #ReturnValue=-1;
Print #ReturnValue
RETURN #ReturnValue;
END CATCH
In my opinion the problem is on selecting the return value from within your stored procedure. I did a quick example in C# with a simple stored procedure.
// demo code to select the return value
string conStr = #"data source=*****; initial catalog=demoDb; integrated security=true";
SqlConnection con = new SqlConnection(conStr);
SqlCommand com = new SqlCommand("declare #return_status int; exec #return_status = demoProcedure; select #return_status", con);
con.Open();
Console.WriteLine(com.ExecuteScalar());
con.Close();
My demo stored procedure
create PROCEDURE demoProcedure
AS
BEGIN
return 1;
END
GO
Found this example at Technet. I hope you can adapt my example to your code! If I did misunderstood your question or anything within my code is wrong - please let me know!
EDIT
While thinking about your problem I noted the following phrase on technet article
Exits unconditionally from a query or procedure. RETURN is immediate
and complete and can be used at any point to exit from a procedure,
batch, or statement block. Statements that follow RETURN are not
executed.
So when you would alter your procedure to select a value instead of returning it you could adapt your code to:
string conStr = #"data source=***; initial catalog=demoDb; integrated security=true";
SqlConnection con = new SqlConnection(conStr);
SqlCommand com = new SqlCommand("demoProcedure", con);
com.CommandType = System.Data.CommandType.StoredProcedure;
con.Open();
Console.WriteLine(com.ExecuteScalar());
con.Close();
with a simple procedure
create PROCEDURE demoProcedure
AS
BEGIN
select 1;
END
EDIT 2
Your stored procedure returns 0 in case of success and -1 in case of a failure. But within your btnClick event your select stmt checks for 1 = success and 0 = failure. Please try changing your code to
protected void btnSubmit_Click(object sender, EventArgs e)
{
string display;
long cardnum;
string strcard = Request.Params.Get("__CREDITCARD");
if (long.TryParse(strcard, out cardnum))
{
// your code goes here ...
switch (retcode)
{
case 0: // changed to reflect returnValue from stored Procedure
// your code goes here ...
return;
case -1: // changed to reflect returnValue from stored Procedure
display = "Invalid credit card number";
break;
}
}
// your code goes here ...
}

Categories