2017-08-02 50 views
0

我想顯示一個信息框說'身份證存在,插入不成功',如果我有一個現有的ID,但有這個錯誤!違反PRIMARY KEY不能在對象'dbo.EventType'中插入重複鍵。重複的鍵值是(6)

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

} 
+1

你有沒有試過調試以發現你爲什麼會遇到「錯誤」的情況? –

+0

[違反PRIMARY KEY約束]的可能重複(https://stackoverflow.com/questions/6796009/violation-of-primary-key-constraint) – VDWWD

回答

0

我想你應該使用try catch塊。根據異常捕獲異常並提供所需的消息。

0

在你的情況,我認爲你的主鍵是自動增量。因此,不要在該主鍵上傳遞值,因爲數據庫會自動增加該字段並插入它。

注意:不要在主自動增量字段中傳遞值。

0

請注意,您對produ的null檢查很奇怪。刪除它或檢查produ!= null。你可以像下面這樣做。請注意,您也可以將try catch放入EventTypeInsert函數中。我認爲會導致更乾淨的代碼。

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 
} 
相關問題