2017-01-03 20 views
-2

如果在MessageBoxButton.YesNo處單擊「否」按鈕,正在輸入的數據仍然會插入到數據庫中。我應該如何解決這個問題?單擊消息框上的「否」將導致數據仍然保存到數據庫中

這是我的代碼:

string insertQuery = "INSERT INTO db_personal(per_image,per_Fname,per_Mname,per_Lname)VALUES(@per_image,@per_Fname,@per_Mname,@per_Lname)"; 

connection.Open(); 

MySqlCommand cmd = new MySqlCommand(insertQuery, connection); 
cmd.Parameters.AddWithValue("@per_image", newPicture.Image); 
cmd.Parameters.AddWithValue("@per_Fname", newFirstName.Text); 
cmd.Parameters.AddWithValue("@per_Mname", newMiddleName.Text); 
cmd.Parameters.AddWithValue("@per_Lname", newLastName.Text); 

try 
{ 
    if (cmd.ExecuteNonQuery() == 1) 
    { 
     MetroFramework.MetroMessageBox.Show(this, "New student information has been successfully saved.", "", MessageBoxButtons.OK, MessageBoxIcon.Information); 
    } 
    else 
    { 
     MetroFramework.MetroMessageBox.Show(this, "Incomplete information. Are you sure you want to save?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question); 
    } 
} 
catch (Exception ex) 
{ 
    MessageBox.Show(ex.Message); 
} 

connection.Close(); 
+0

檢查一下MessageBox的調用返回。 – SLaks

+1

那麼......不要執行查詢,直到*之後*他們選擇是 – musefan

+0

您的代碼片段不顯示任何消息框處理 – Takarii

回答

1

首先運行查詢:

if (cmd.ExecuteNonQuery() == 1) 

並檢查結果看你想要什麼樣的信息顯示。此時數據已經保存到數據庫中或沒有。然後你問用戶是否仍希望將數據保存到數據庫中,但什麼都不做處理這些信息,你會想要做的事,如:

DialogResult dr = MetroFramework.MetroMessageBox.Show(this, "Incomplete information. Are you sure you want to save?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question); 

if (dr == DialogResult.Yes) 
{ 
    //Handle saving, although it probably already has been 
    //Ask to re-enter the data? 
} 
else 
{ 
    //Rollback the previous command 
} 

我從未有過回滾命令到數據庫但我發現方法SqlTransaction.Rollback,但我不知道它是如何工作的或者它是否適用。

你應該想想,使其流動重拾你的邏輯更好:

  1. 檢查輸入數據看起來不如預期,所有的驗證程序
  2. 詢問用戶,如果他們真的想保存的信息
  3. IF是保存數據

因此,像:

//Some validation 

DialogResult dr = MessageBox.Show("Do you want to save the information?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question); 
if (dr == DialogResult.Yes) 
{ 
    var result = cmd.ExecuteNonQuery(); 

    //Do something with the result here 
} 

如果驗證檢查失敗,但它仍與該數據庫兼容,你也可以用一個消息呈現給用戶,如果他們還想繼續:

DialogResult dr = MessageBox.Show("Incomplete information. Are you sure you want to save?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question); 
if (dr != DialogResult.Yes) 
{ 
    //Do not save the data 
} 
相關問題