Click here to Skip to main content
15,891,688 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
when I insert a record into the database that record is already exist means how to convey that information by the message display?
Now I add the primary key for the Reg.No, I already insert the Reg.No"123", then I insert again one more time means that time I convey this message "Already Exist" by the message box. How can I do it? Please Help me, Friend....!
Posted
Updated 15-Apr-14 18:27pm
v2

First , if its primary key you need not to insert any value for it, but if any other than that you need to check then you can make a check into database itself.
In database side:
SQL
CREATE PROCEDURE Sb_inserupdate
(
	@Idcol int --your column
)
AS
BEGIN
	IF EXISTS (SELECT 1 FROM yourtable WHERE Idcol = @Idcol)
        SELECT 0 --means record exists
    ELSE
        --insert query to insert record
        SELECT 1
END
GO

Coding side:
C#
using (SqlConnection con = new SqlConnection(constr))// your connection
{
SqlCommand cmd = new SqlCommand();
    cmd.CommandText = "Sb_inserupdate";
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("@Idcol", clientID);
Int32 val = Convert.ToInt32(cmd.ExecuteScalar());
if (val ==0)
{
	//show msg record exists;
}
else
{
	//next action
}
 
Share this answer
 
Try this:
C#
SqlCommand cmd = new SqlCommand(queryhere, con);//use parameterized query
 SqlDataReader  dr=cmd.ExecuteReader();
   dr.Read();
   if (dr.HasRows)
   {
       dr.Close();
     ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "alert('Already Exists!..')", true);
   }
   else
   {
   //insert query here
   }
 
Share this answer
 
v3
Comments
Member 10624163 16-Apr-14 0:52am    
can you give the detailed solution for this friend?
Tom Marvolo Riddle 16-Apr-14 1:00am    
we're ready to help you .will you please explain what you need more than this?
You can check the record exist or not before insert the new record.

C#
string sql = "select * from tablename where regno='" + txtRegNo.Text +"'";

database db = new DataBase();
 result = (int) db.GetScalar(sql);
if(result > 0)
{
Show Message
}
else
{
insert new record
}
 
Share this answer
 

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