Click here to Skip to main content
15,916,842 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a form which stores staff records. I want the form to check in sql db to
see if a staff id exists and display "The Staff ID Already Exist" instead of the
normal error message "violation of primary constraint ...." when the save button is
clicked. I tried this but it only checks for the first row in the table but if the staffid
is in the subsequent rows it displays the normal error message.

Please help me out.

Code behind form:

C#
private void btnSave_Click(object sender, EventArgs e)
        {

            SqlConnection conn = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString"]);
            conn.ConnectionString = "Data Source=MICKY-PC;Initial Catalog=SMS;User ID=sa;Password=mike";
            conn.Open();
            
            //save data
            try
            {
                if (!validateScreen())
                    return;
                clsStaffpersonal person = new clsStaffpersonal();
                             
                SqlCommand cmd = new SqlCommand("SELECT * FROM tblstaffpersonaldetails", conn);

                SqlDataReader dr = cmd.ExecuteReader();

            if (dr.Read())
            {
                if (this.txtStaffid.Text != dr["staffid"].ToString())
                {
                                    
                var
                _with1 = person;
                _with1.ID = this.txtStaffid.Text;
                _with1.myPicture = lblPicture.Text;
                _with1.entitle = cboTitle.Text;
                _with1.Sname = txtSurname.Text;
                _with1.Mname = txtMiddlename.Text;
                _with1.Fname = txtFirstname.Text;
                
                _with1.saveRegister();

                else
                {
                    MessageBox.Show("The Staff ID Already Exist");
                    return;
                }
            }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }


Code in class:

C#
public void saveRegister()
       {
           //saves the data in memory


           SqlCommand cmd = new SqlCommand();
           string dat = null;
           dat = dateofbirth.Year + "-" + dateofbirth.Month + "-" + dateofbirth.Day;
           string sqlQuery = null;
           sqlQuery = "Insert into tblstaffpersonaldetails values('" + staffid + "','" + title + "','" + surname + "','" + middlename + "','" + firstname + "','" + gender + "','" + dat + "','" + age + "','" + nationality + "','" + religion + "','" + maritalstatus + "','" + spousename + "','" + numberofchildren + "','" + emergencycontactnumber + "','" + residentialaddress + "','" + postaladdress + "','" + contactnumber + "','" + contactnumber2 + "','" + email + "','" + nameofnok + "','" + nokcontactnumber + "','" + idtype + "','" + idnumber + "','" + idexpirydate + "','" + picture + "')";
           // sqlQuery = "Insert into tblstaffpersonaldetails values('" + client_id + "',dbo.ProperCase('" + surname + "'),'" + othername + "','" + gender + "','" + dat + "','" + age + "','" + nationality + "','" + residential_address + "','" + postal_address + "','" + contact_number + "','" + marital_status + "','" + spouse_name + "','" + email + "','" + occupation + "','" + typeof_id + "','" + id_number + "','" + id_expirydate + "','" + remarks + "','" + picture + "','" + active_status + "')";


           cmd.Connection = conn;
           cmd.CommandText = sqlQuery;
           cmd.CommandType = System.Data.CommandType.Text;
           conn.Open();
           cmd.ExecuteNonQuery();
           cmd.Dispose();
           conn.Close();
       }
Posted
Updated 10-Jul-12 6:00am
v2

In the btnSave_Click please modify as shown below

C#
...
SqlCommand cmd = new SqlCommand(string.Format("SELECT * FROM tblstaffpersonaldetails WHERE StaffId='{0}'", this.txtStaffid.Text), conn);
SqlDataReader dr = cmd.ExecuteReader();

if (dr.HasRows)
{
    // Id already present
}
else
{
    // Id is not present. So you can create a new record.
}


If the solution works please click like.

All the Best
Kiran
 
Share this answer
 
Comments
mikeoabban 10-Jul-12 13:46pm    
thanks alot it was perfect
You should do the insert through a stored procedure, passing parameters rather than constructing sql in code.

One way (of many) to do this is to wrap the process in a try/catch - transaction inside a stored procedure which, if it fails, returns a value that you can inspect and then take the appropriate action:

SQL
-- Wrap in try catch to return success/failure.
begin try

	-- Wrap in a transaction.
	begin tran

		-- Add new record.
		insert into Table (Field1, Field2, Field3)
		values (@Param1, @Param2, @Param3)

	-- Commit the transaction.
	commit tran

	-- If we get here it succeeded.
	select 1 [Result]

end try
begin catch

	-- Transaction failed?
	if @@trancount > 0
	begin
		-- Undo.
		rollback
	end

	-- Let the app know that it failed.
	select 0 [Result]

end catch


Another way might be to pass the staffid and test that with:

SQL
if (not exists(select top 1 1 from Table where StaffID = @StaffID))
begin
	insert into Table (Field1, Field2, Field3)
	values (@Param1, @Param2, @Param3)
end


Use or adapt either of these methods to suit your need but you should certainly consider wrapping everything into a stored procedure and call that rather thna constructing a sql string in code.
 
Share this answer
 
Comments
AshishChaudha 10-Jul-12 12:48pm    
my 5!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900