0

i want to show a msg box saying 'id exists, insert not successful' if i have an existing id but there is this error !!

 protected void Button1_Click(object sender, EventArgs e)
{
    int result = 0;

    EventType produ = new EventType(int.Parse(tb_id.Text), tb_Name.Text);
    result = produ.EventTypeInsert();

    if (produ == null)
    {
        if (result > 0)
        {
            Response.Write("<script>alert('Insert successful');</script>");
        }
        else
        {
            Response.Write("<script>alert('Insert NOT successful');</script>");
        }
    }
    else
    {
        Response.Write("<script>alert('ID already exists.Insert NOT successful');</script>");
    }

}
jay
  • 3
  • 3
  • 1
    Have you ever tried to debug to find out why you're running into the "wrong" condition? – Mighty Badaboom Aug 02 '17 at 07:53
  • Possible duplicate of [Violation of PRIMARY KEY constraint](https://stackoverflow.com/questions/6796009/violation-of-primary-key-constraint) – VDWWD Aug 02 '17 at 09:33

3 Answers3

0

I think you should use try catch block. Catch the exception and provide the message you want depending on the exception.

Crekate
  • 145
  • 1
  • 10
0

In your case, i think your primary key is auto incremental. So, do not pass value in that primary key because database will auto increment that field and insert it.

Note: Do not pass value in Primary Auto Incremented Field.

0

Note that your check for null on produ is strange. Remove it or check if produ != null. You could do it like below. Note that you could also place the try catch in the EventTypeInsert function. I think will result in cleaner code.

int result = 0;
try
{
    EventType produ = new EventType(int.Parse(tb_id.Text), tb_Name.Text);       
    result = produ.EventTypeInsert();

    if (result > 0)
    {
        Response.Write("<script>alert('Insert successful');</script>");
    }
    else
    {
        Response.Write("<script>alert('Insert NOT successful');</script>");
    }
}
catch (SqlException ex)
{
     Response.Write("<script>alert('ID probably already exists.Insert NOT successful');</script>");
}
catch (Exception ex)
{
     // maybe log a general error
}
drsbee
  • 96
  • 1
  • 3