嘿所以我有下面的代码应该抛出错误,如果文本框是空的,但它不只是继续与它会做什么,他们不是,并添加一个项目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