2014-02-20 169 views
3

我已經創建了函數將信息添加到數據庫的窗體窗體。但是,我有一個問題。當我在「產品代碼」列中鍵入這樣一個數字「SM0001」,然後按回車鍵時,它將數據存儲到數據庫,當我鍵入與之前輸入的數字相同的數字時,它不會阻止用戶輸入「產品代碼」已經存在於數據庫中。所以,這是我目前的數據庫(在系統中顯示在DataGridView):在System.Data.dll中發生未處理的類型'System.Data.OleDb.OleDbException'的異常c#

enter image description here

正如你看到的,行「1」和行「2」具有相同的「產品編號」 ..我的問題是:我如何防止用戶輸入兩次相同的號碼?

我已經改變數據庫中的主鍵「產品編號」,但這裏是我得到的錯誤:

的錯誤是:

An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll 

Additional information: The changes you requested to the table were not successful because they would create duplicate values in the index, primary key, or relationship. Change the data in the field or fields that contain duplicate data, remove the index, or redefine the index to permit duplicate entries and try again. 

的錯誤是:

cmd.ExecuteNonQuery();

此功能:

private void AddDatabase(object sender, EventArgs e) 
     { 
      using (OleDbConnection conn = new OleDbConnection(connectionString)) 
      { 
       string query = "INSERT INTO [Table] ([ProductCode], [Description], [Price]) VALUES (@ProductCode, @Description, @Price)"; 
       conn.Open(); 
       using (OleDbCommand cmd = new OleDbCommand(query, conn)) 
       { 
        cmd.Parameters.Add("@ProductCode", System.Data.OleDb.OleDbType.VarChar); 
        cmd.Parameters["@ProductCode"].Value = this.numericTextBox1.Text; 
        cmd.Parameters.Add("@Description", System.Data.OleDb.OleDbType.VarChar); 
        cmd.Parameters["@Description"].Value = this.textBox3.Text; 
        cmd.Parameters.Add("@Price", System.Data.OleDb.OleDbType.Integer); 
        cmd.Parameters["@Price"].Value = this.textBox4.Text; 
        cmd.ExecuteNonQuery(); // The error is here 
        if (_choice.comboBox1.Text == "English") 
        { 
         System.Media.SoundPlayer _sound = new System.Media.SoundPlayer(@"C:\Windows\Media\Windows Exclamation.wav"); 
         _sound.Play(); 
         DialogResult _dialogResult = MessageBox.Show("Added Successfully!", "Success", MessageBoxButtons.OK); 
         if (_dialogResult == DialogResult.OK) 
         { 
          ViewDatabase(sender, e); 
          ClearTextBoxes(sender, e); 
         } 
        } 
       } 
       conn.Close(); 
      } 
     } 

我想當用戶鍵入相同的「產品代碼」時,消息框將顯示不允許輸入「產品代碼」,因爲它存在於數據庫中,並且不會給出錯誤(終止程序運行) 。

我該如何解決?

謝謝

您的回答將不勝感激!

+0

我想ü使用的數據集/表作爲數據源? – User999999

+0

有很多方法可以解決您的問題,但您的問題的直接答案是try/catch/finally塊。然後你可以使用數據庫代碼,一個帶有鍵/約束的本地'DataTable'等。 –

回答

2

你得到的錯誤是很正常的。您不能將重複項插入主鍵(也不能包含'NULL')列。有關主鍵的更多信息:

W3schools - primary key

database.about.com

之前執行AddDatabase你應該檢查開關是否已經存在於數據庫中。你可以用許多不同的方式來做到這一點。

  1. 執行SELECT數據庫

    SELECT TOP 1 ProductCode FROM Table WHERE ProductCode = 'this.numericTextBox1.Text'" 
    

    上如果此查詢產生一個結果,則產品代碼已經存在於數據庫和查詢應執行

  2. 檢查你的datagridview的數據源

    作爲你的datagridview的數據源,你是probabl y提供一個List/Dataset。您可以檢查您的列表是否存在新輸入的ProductCode。你可以在這裏使用鏈接或只是迭代源代碼。(不管你的船浮筒)

    如果你可以給我的數據源的類型,那麼我可能會提供一個代碼示例

  3. 檢查您的datagridview

    如果您的datagridview包含數據庫的所有記錄,那麼你可以迭代這些行並檢查第一列是否包含等於新輸入的產品代碼的產品代碼。

    東西

    foreach (DataGridViewRow row in dgvDataGridView.Rows) 
         { 
         if(row.Cells[0].Value.toString().equals(this.numericTextBox1.Text)) 
    
          { 
    
          // Productcode is already present 
          // Throw message/exception Or whatever 
          break; 
          } 
         } 
    

在電線之間我會選擇選項1,因爲你的DataGridView /數據源可能不會顯示/保存所有記錄Table

+0

謝謝先生!它的工作原理 – Kaoru

+0

沒問題!玩得開心:) – User999999

1

執行INSERT您可以檢查之前如果數據庫已經包含ProductCode(這似乎是在您的表中)。

喜歡的東西(從我的項目之一複製/粘貼代碼,但應該清楚)

var command = new OleDbCommand("SELECT COUNT(*) FROM results WHERE id = ?", _connection); 
command.Parameters.Add("id", OleDbType.Date).Value = id; 
if ((int)command.ExecuteScalar() == 0) 
{ 
    // not exists 
} 

建議:不要讓AddDatabase事件處理程序,而是創建一個單獨的類來處理數據庫的操作,使方法AddDatabase那裏並從事件處理程序調用它。

你可以有2種方法則Exists(id)Add(...),所以在事件中,你可以做簡單的重複檢查:

if(Database.Exists(id)) 
{ 
    // show errror 
    return; 
} 
DataBase.Add(...); 
+0

非常感謝您的先生! – Kaoru

相關問題