2017-10-04 18 views
-1

如何驗證txtPName和txtAddress是否爲空我無法繼續提交併彈出消息框。如何驗證某些空的文本框

private void btnSubmit_Click(object sender, EventArgs e) 
    { 

     string insertQuery = "INSERT INTO patientdb.addpatient(PatientName,MobileNumber,Occupation,Gender,Address,Age,PhoneNumber,MedicalHistory,ChiefComplaint) VALUES ('" + txtPName.Text + "','" + txtMNum.Text + "','" + txtOccup.Text + "','" + comboBox1.Text + "','" + txtAddress.Text + "','" + txtAge.Text + "','" + txtPNum.Text + "','" + rtbMHistory.Text + "','" + rtbCC.Text + "')"; 
     con.Open(); 
     MySqlCommand command = new MySqlCommand(insertQuery, con); 

     try 
     { 
      if (command.ExecuteNonQuery() == 1) 
      { 
       MessageBox.Show("Data Inserted"); 
       txtPName.Text = ""; 
       txtMNum.Text = ""; 
       txtPNum.Text = ""; 
       txtAddress.Text = ""; 
       txtAge.Text = ""; 
       txtOccup.Text = ""; 
       rtbMHistory.Text = ""; 
       rtbCC.Text = ""; 
       comboBox1.Text = " "; 
      } 
      else 
      { 
       MessageBox.Show("Data Not Inserted"); 
      } 
     } 
+1

你有沒有嘗試過什麼? http://idownvotedbecau.se/noattempt/ – Amy

+0

你的意思只是一個簡單的如果之前提交? – Farshad

+0

你已經使用了一個'if'語句,所以你必須知道如何寫另一個。對?所以有什麼問題? – Amy

回答

0

您可以在執行其餘代碼之前添加驗證檢查。調用return將在驗證失敗後立即離開該方法。

private void btnSubmit_Click(object sender, EventArgs e) 
{ 
    if (string.IsNullOrEmpty(txtPName.Text) || string.IsNullOrEmpty(txtAddress.Text)) 
    { 
     MessageBox.Show("Missing Data"); 
     return; 
    } 

// Your code here... 
+0

感謝您爲此添加了con.Close();之前返回,因爲我得到一個錯誤,說連接已打開,當我試圖輸入新的,但謝謝你的答案,現在我明白了 –