-2

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;
        }
    }
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

2 Answers2

1

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.

Steve
  • 213,761
  • 22
  • 232
  • 286
  • using Convert.ToInt32(StaffID) gave error No overload for method 'ManageUser' takes 9 arguments as i haven't defined field for StaffID on form. Please help. – Krishna Pariyar Dec 04 '14 at 21:00
  • Notice that I have added that string _staffID_ to the other parameters received by the method _ManageUser_. Before this change there were 9 parameters now you have 10 parameters. This means that every call to _ManageUser_ should pass that extra parameter. – Steve Dec 04 '14 at 21:06
  • As I have said in my answer, you NEED it, otherwise you can't delete or update. So, when you load the user for editing save the value for StaffID and pass it back when you save. – Steve Dec 04 '14 at 21:10
  • so what should i pass for StaffID in ManageUser as i don't have field for StaffID on the form as txtUserName.Text for Username. Please help. – Krishna Pariyar Dec 04 '14 at 21:11
  • If UserName has an UNIQUE index then you could use it for DELETE and UPDATE. Do you have unique usernames in your table? – Steve Dec 04 '14 at 21:12
  • yes, i have unique usernames – Krishna Pariyar Dec 04 '14 at 21:13
  • Rethinking about UserName, with UserName you need to save the old username before editing and pass the new one and the old one. Better use StaffID, you just need to store the value for StaffID when you load the user and pass it back to ManageUser – Steve Dec 04 '14 at 21:19
  • I am very new in C# .net . Thank you for your help.Please help to store the value for StaffID when loading the user and passing it back to Manage User. How can i use in my code?It would have been better if we could chat if you have free time for help. :) – Krishna Pariyar Dec 04 '14 at 21:27
  • It is not possible for you to use the chat. You need more rep. Please, could you add to your question above the code used to initialize the textboxes with the user values when you want to edit/delete an existing user? – Steve Dec 04 '14 at 21:34
  • Sorry @CrshnaPariyar but that's the code to SAVE a new User. I mean the code used to load a user and pass the loaded user data in the textbox where your user could edit them. Probably this code is in your Form.Load event – Steve Dec 04 '14 at 22:14
  • I have added the code to load Users in textbox. Please have a look. – Krishna Pariyar Dec 04 '14 at 22:33
  • The UserClass.SelectAllUsers probably executes some kind of SQL like this "SELECT * from tbl_Staff", here there is the StaffID value that is stored in the datagridview rows. So you have it, probably at the column at index 0 (an hidden column?). You can retrive its value with datagridView.Rows[Index].Cells[0].Value. – Steve Dec 04 '14 at 22:42
  • Yes as you mentioned the UserClass.SelectAllUser executes "Select * from tbl_Staff".I tried the retrive code you suggested but couldn't figure out the error. Actually where should i use datagridView.Rows[Index].Cells[0].Value? – Krishna Pariyar Dec 04 '14 at 23:13
  • You should have somewhere in your program a piece of code that extracts data from the selected row in the grid and set this data in the textbox. (something like txtFullName.Text = gridview.Row[??].Cells[1].Value) The code to read the StaffID is identical. You need only to find the correct index to use for the cell with the StaffID value. The code to set a variable with the value of the current row StaffOD should be written just before calling ManageUser. Now, I am sorry to say, but for me it is time to go to bed. Goodnight and good luck. – Steve Dec 04 '14 at 23:46
  • For examples on reading values from a datagridview http://stackoverflow.com/questions/6487839/reading-data-from-datagridview-in-c-sharp – Steve Dec 04 '14 at 23:49
  • Thank you for your help Steve. The problem is solved now. Now i am able to delete and update table. – Krishna Pariyar Dec 05 '14 at 23:43
0

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);
    ....
}
}
prasy
  • 250
  • 1
  • 14