我已經創建了函數將信息添加到數據庫的窗體窗體。但是,我有一個問題。當我在「產品代碼」列中鍵入這樣一個數字「SM0001」,然後按回車鍵時,它將數據存儲到數據庫,當我鍵入與之前輸入的數字相同的數字時,它不會阻止用戶輸入「產品代碼」已經存在於數據庫中。所以,這是我目前的數據庫(在系統中顯示在DataGridView):在System.Data.dll中發生未處理的類型'System.Data.OleDb.OleDbException'的異常c#
正如你看到的,行「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();
}
}
我想當用戶鍵入相同的「產品代碼」時,消息框將顯示不允許輸入「產品代碼」,因爲它存在於數據庫中,並且不會給出錯誤(終止程序運行) 。
我該如何解決?
謝謝
您的回答將不勝感激!
我想ü使用的數據集/表作爲數據源? – User999999
有很多方法可以解決您的問題,但您的問題的直接答案是try/catch/finally塊。然後你可以使用數據庫代碼,一個帶有鍵/約束的本地'DataTable'等。 –