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

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

Related

Check if username exist in asp.net using stored procedure and adding values to Registration.aspx

I've created a stored procedure in SQL Server to check if username exists in the database:
CREATE PROCEDURE [dbo].[spCheckUsernameForAnswer]
#username VARCHAR(30)
AS
BEGIN
DECLARE #count INT
SELECT #count = COUNT(username)
FROM Users
WHERE [username] = #username
IF (#count = 1)
BEGIN
SELECT 1 AS ReturnCode
END
ELSE
BEGIN
SELECT 0 AS Returncode
END
END
Here is what I've done in Visual Studio Registration.aspx.cs.
I need to check if the username exists and if not to insert the required values into db to register a new user.
From the code below it keeps registering new users with the same username again and again.
Any idea what am I missing here?
protected void Button1_Click(object sender, EventArgs e)
{
try
{
Guid newGUID = Guid.NewGuid();
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand("spCheckUsernameForAnswer", conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter parausername = new SqlParameter("#username", TextBoxUN.Text);
cmd.Parameters.Add(parausername);
conn.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
if (Convert.ToBoolean(rdr["ReturnCode"]))
{
Label1.Text = "Username found";
}
else
{
Label1.Text = "not found";
}
}
conn.Close();
SqlConnection conn1 = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn1.Open();
string insertQuery = "insert into [Users] (user_id, first_name, last_name, email, username, password) values (#user_id, #first_name, #last_name, #email, #username, #password)";
SqlCommand com = new SqlCommand(insertQuery, conn1);
com.Parameters.AddWithValue("#user_id", newGUID.ToString());
com.Parameters.AddWithValue("#first_name", TextBoxFname.Text);
com.Parameters.AddWithValue("#last_name", TextBoxLname.Text);
com.Parameters.AddWithValue("#email", TextBoxEmail.Text);
com.Parameters.AddWithValue("#username", TextBoxUN.Text);
com.Parameters.AddWithValue("#password", TextBoxPass.Text);
com.ExecuteNonQuery();
Response.Write("Registration successful");
conn1.Close();
}
}
catch (Exception ex)
{
Response.Write("Error:" + ex.ToString());
}
It's better use cmd.ExecuteScalar since the sp is returning either 1 or 0.
And it would be better to have the insert into db part in a separate method like RegisterUser method.
But the main thing is you need to call that method when it doesn't exist in db (in the else statement)
protected void Button1_Click(object sender, EventArgs e)
{
try
{
using(var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString))
{
using(var cmd = new SqlCommand("spCheckUsernameForAnswer", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#username", TextBoxUN.Text));
conn.Open();
var returnCode = Convert.ToInt32(cmd.ExecuteScalar());
if(returnCode == 1)
{
Label1.Text = "Username found";
}
else
{
Label1.Text = "not found";
Register();
}
}
}
}
catch (Exception ex)
{
Response.Write("Error:" + ex.ToString());
}
}
private void RegisterUser()
{
try
{
var newGUID = Guid.NewGuid();
using(var conn1 = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString))
{
conn1.Open();
string insertQuery = "insert into [Users] (user_id, first_name, last_name, email, username, password) values (#user_id, #first_name, #last_name, #email, #username, #password)";
using(var com = new SqlCommand(insertQuery, conn1))
{
com.Parameters.AddWithValue("#user_id", newGUID.ToString());
com.Parameters.AddWithValue("#first_name", TextBoxFname.Text);
com.Parameters.AddWithValue("#last_name", TextBoxLname.Text);
com.Parameters.AddWithValue("#email", TextBoxEmail.Text);
com.Parameters.AddWithValue("#username", TextBoxUN.Text);
com.Parameters.AddWithValue("#password", TextBoxPass.Text);
com.ExecuteNonQuery();
}
}
Response.Write("Registration successful");
}
catch (Exception exc)
{
//log the exception;
}
}
Try this not too sure why you used reader if i was you will handle everything in stored procedure
protected void Button1_Click(object sender, EventArgs e)
{
try
{
Guid newGUID = Guid.NewGuid();
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand("spCheckUsernameForAnswer", conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter parausername = new SqlParameter("#username", TextBoxUN.Text);
cmd.Parameters.Add(parausername);
conn.Open();
var userexsist = (bool)cmd.ExecuteScalar();
if (userexsist)
{
Label1.Text = "Username found";
conn.close();
}
else
{
Label1.Text = "not found";
string insertQuery = "insert into [Users] (user_id, first_name, last_name, email, username, password) values (#user_id, #first_name, #last_name, #email, #username, #password)";
SqlCommand com = new SqlCommand(insertQuery, conn);
com.Parameters.AddWithValue("#user_id", newGUID.ToString());
com.Parameters.AddWithValue("#first_name", TextBoxFname.Text);
com.Parameters.AddWithValue("#last_name", TextBoxLname.Text);
com.Parameters.AddWithValue("#email", TextBoxEmail.Text);
com.Parameters.AddWithValue("#username", TextBoxUN.Text);
com.Parameters.AddWithValue("#password", TextBoxPass.Text);
com.ExecuteNonQuery();
Response.Write("Registration successful");
conn.Close();
}
}
catch (Exception ex)
{
Response.Write("Error:" + ex.ToString());
}
}
You can manage it in stored procedure also. Find the solution:
USE [akhil_db]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[Sp_Insert_AddUser]
(
#fname varchar(200),
#lname varchar(200),
#userName varchar(200),
#userEmail varchar(200),
#userPasword varchar(200),
#userType varchar(200),
#msg VARCHAR(100) OUT )
AS
BEGIN
SET NOCOUNT ON;
Declare #UserCount int;
SELECT #UserCount = COUNT(*) FROM user_master WHERE [user_name] = #userName or [user_email]=#userEmail;
IF(#UserCount > 0)
begin
Set #msg = 'User already exists';
end
ELSE
begin
Insert into user_master(
user_fname,
user_lname,
[user_name]
,[user_email]
,[user_pasword]
,user_type
)
values(
#fname,
#lname,
#userName
,#userEmail
,#userPasword
,#userType
)
SET #msg ='Registered Successfully'
END
END
Code behind c#
SqlCommand cmd = new SqlCommand("Sp_Insert_AddUser", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#fname", txtfname.Text);
cmd.Parameters.Add("#lname", txtlname.Text);
cmd.Parameters.AddWithValue("#userName", txtUserName.Text);
cmd.Parameters.AddWithValue("#userEmail", txtUserEmail.Text);
cmd.Parameters.AddWithValue("#userPasword", txtPass.Text);
cmd.Parameters.AddWithValue("#userType", ddlUserType.SelectedValue);
cmd.Parameters.Add("#msg", SqlDbType.Char, 500);
cmd.Parameters["#msg"].Direction = ParameterDirection.Output;
con.Open();
cmd.ExecuteNonQuery();
string message = (string)cmd.Parameters["#msg"].Value;
lblMessage.Visible = true;
lblMessage.Text = message;
con.Close();
I'M USING HELPER CLASS VS. SOON I WILL SENT ALTERNATIVE SOLUTION
SqlHelper sho = new SqlHelper();
public bool alreadyexist()
{
string[] str = { "#catname", "#proname" };
string[] obj = { comboproductname.Text, comboitemname.Text };
SqlDataReader sdrr = sho.GetReaderByCmd("sp_item_alreadyex", str, obj);
if (sdrr.Read())
{
sdrr.Close();
sho.CloseConnection();
return true;
}
else
{
sdrr.Close();
sho.CloseConnection();
return false;
}
Stored procedure:
Create procedure [dbo].[sp_item_alreadyex]
#catname nvarchar(50),
#proname nvarchar(50)
as
begin
select *
from Item
where Item_Name = #proname and Category = #catname
end

Insert Select with Same Store Procedure

I am working on website with C#.I have Store Registration Details in two table that is login and registration.Data is inserted in table. Now when i am on login page this email_id and pasword is selected from Database.So, for that i have created one Store procedure which is`
ALTER PROCEDURE [dbo].[P_M_Login]
#Email_id nvarchar(50),
#Password nvarchar(50),
#Tran_Type nvarchar(1)
AS
BEGIN
SET NOCOUNT ON;
IF #Tran_Type='I'
if not exists(select 1 from M_Login where Email_id=#Email_id)
BEGIN
INSERT INTO M_Login ( Email_id, Password)
VALUES(#Email_id,#Password);
end
ELSE
IF #Tran_Type='S'
BEGIN
Select Email_id,Password from M_Login;
END
END`
Now i want to use this Store Procedure in my three tier architecture how can i pass tran type so it will be perfect for me.
This is my DAL Class coding for calling store procedure.
public Int32 Login(BALRegistration objBEL)
{
int result;
try
{
SqlCommand cmd1 = new SqlCommand("P_M_Login", con);
cmd1.CommandType = CommandType.StoredProcedure;
//cmd.Parameters.AddWithValue("#Regisration_Id", objBEL.Registration_Id);
cmd1.Parameters.AddWithValue("#Email_id", objBEL.Email_id);
cmd1.Parameters.AddWithValue("#Password", objBEL.Password);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
result = cmd1.ExecuteNonQuery();
cmd1.Dispose();
if (result > 0)
{
return result;
}
else
{
return 0;
}
}
catch (Exception ex)
{
throw;
}
finally
{
if (con.State != ConnectionState.Closed)
{
con.Close();
}
}
}
}
}
Try this. Since you have parameter to be accepted in stored procedure, you just need to pass the parameter from the DAL
string type="s";
SqlCommand cmd1 = new SqlCommand("P_M_Login", con);
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Parameters.AddWithValue("#Email_id", objBEL.Email_id);
cmd1.Parameters.AddWithValue("#Password", objBEL.Password);
cmd1.Parameters.AddWithValue("#Tran_Type ", type);

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 ...
}

executenonquery not working in for loop

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

How to acces a flag set in sql server into business logic

public int InsertCompanyDetailsInformation(int companyId, int bankId, int accountNo, string accountType)
{
int rowsAffected = -1;
int returnValue;
try
{
SqlConnection con = DBProvider.GetDbConnection();
using (con)
{
con.Open();
SqlCommand objCmd = new SqlCommand("dbo.sp_InsertCompanyDetailsInformation", con);
objCmd.CommandType = CommandType.StoredProcedure;
objCmd.Parameters.AddWithValue("#companyId", companyId);
objCmd.Parameters.AddWithValue("#bankId", bankId);
objCmd.Parameters.AddWithValue("#accountNo", accountNo);
objCmd.Parameters.AddWithValue("#accountType", accountType);
rowsAffected = objCmd.ExecuteNonQuery();
SqlParameter sqlParam = objCmd.Parameters.Add("#insert_flag", SqlDbType.Int);
objCmd.Parameters["#insert_flag"].Direction = ParameterDirection.ReturnValue;
returnValue = int.Parse(objCmd.Parameters["#insert_flag"].Value.ToString());
con.Close();
}
}
catch (Exception ex)
{
throw ex;
}
return rowsAffected;
}
and stored procedure
USE [SGTime_Development]
GO
/****** Object: StoredProcedure [dbo].[sp_InsertCompanyDetailsInformation] Script Date: 01/04/2011 14:31:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[sp_InsertCompanyDetailsInformation]
(
#companyId int,
#bankId int,
#accountNo int,
#accountType varchar(50))
AS
BEGIN
SET NOCOUNT ON;
declare #insert_flag int;
if not exists(select AccountNo from [Company_Account_Details] where AccountNo=#accountNo)
begin
INSERT INTO [Company_Account_Details]
( Company_Id,
BankID,
AccountNo,
AccountType)
values
(#companyId,
#bankId,
#accountNo,
#accountType)
set #insert_flag=1;
END
else
begin
set #insert_flag=-1;
end
return #insert_flag;
end
I am getting error in the code i want return returnValue in InsertCompanyDetailsInformation Please help how we can return returnValue
You need to add parameter for return value before you execute the command. So you need to change code as below:
...
objCmd.Parameters.AddWithValue("#accountType", accountType);
// Add parameter for return value
SqlParameter sqlParam = objCmd.Parameters.Add("#insert_flag", SqlDbType.Int);
objCmd.Parameters["#insert_flag"].Direction = ParameterDirection.ReturnValue;
// now execute the command
rowsAffected = objCmd.ExecuteNonQuery();
// you should able to get return value now
returnValue = int.Parse(objCmd.Parameters["#insert_flag"].Value.ToString());
...
public int InsertCompanyDetailsInformation(int companyId, int bankId, int accountNo, string accountType)
{
int rowsAffected = -1;
int returnValue;
try
{
SqlConnection con = DBProvider.GetDbConnection();
using (con)
{
con.Open();
SqlCommand objCmd = new SqlCommand("dbo.sp_InsertCompanyDetailsInformation", con);
objCmd.CommandType = CommandType.StoredProcedure;
objCmd.Parameters.AddWithValue("#companyId", companyId);
objCmd.Parameters.AddWithValue("#bankId", bankId);
objCmd.Parameters.AddWithValue("#accountNo", accountNo);
objCmd.Parameters.AddWithValue("#accountType", accountType);
rowsAffected = objCmd.ExecuteNonQuery();
SqlParameter sqlParam = objCmd.Parameters.Add("#insert_flag", SqlDbType.Int);
sqlParam.Direction = ParameterDirection.ReturnValue;
// now execute the command
objCmd.Parameters.Add(sqlParam);
con.Open();
rowsAffected = objCmd.ExecuteNonQuery();
con.Close();
returnvalue = (int)objCmd.Parameters["insert_flag"].Value;
}
}
catch (Exception ex)
{
throw ex;
}
return rowsAffected;
}
}

Categories