嘿所以我有下面的代碼應該拋出錯誤,如果文本框是空的,但它不只是繼續與它會做什麼,他們不是,並添加一個項目0或其他任何東西,而不是我的代碼有問題嗎?嘗試捕獲驗證空文本框
private void BtnAdd_Click(object sender, EventArgs e)
{
try
{
theVisit.name = txtName.Text;
theVisit.address = txtAddress.Text;
theVisit.arrival = DateTime.Parse(txtArrival.Text);
//Update theVisit object to reflect any changes made by the user
this.Hide();
//Hide the form
}
catch (Exception)
{
if (txtName.Text == "")
MessageBox.Show("please enter a customer name");
if(txtAddress.Text == "")
MessageBox.Show("Please enter a customer address");
if(txtArrival.Text == "")
MessageBox.Show("Please enter an arrival time");
}
新
if (txtName.Text == "" || txtAddress.Text == "" || txtArrival.Text == "")
MessageBox.Show(" Please enter a value into all boxes");
else
theVisit.name = txtName.Text;
theVisit.address = txtAddress.Text;
theVisit.arrival = DateTime.Parse(txtArrival.Text);
//Update theVisit object to reflect any changes made by the user
那裏可能拋出的唯一事情是DateTime.Parse()。空文本框上的'.Text'不會引發異常,它只是返回一個空字符串。使用'string.IsNullOrEmpty(txtName.Text)'檢查空值。 – drch
您的theVisit對象的setter是否會拋出異常?你能否顯示你的theVisit對象的類實現? –
theVisit是一個列表,但我想我通過把它放在try not catch部分 – TAM