我有一个名为 AddEditReminderForm 的抽象窗体,其中包含一个事件处理程序和一个方法:
以下是 AddEditReminderForm 的相关代码:
protected virtual void buttonSave_Click(object sender, EventArgs e)
{
title = textboxTitle.Text;
description = textboxDescription.Text;
place = textboxPlace.Text;
date = datePicker.Value.Date;
time = timePicker.Value.TimeOfDay;
PerformValidations();
}
protected void PerformValidations()
{
if (String.IsNullOrEmpty(title))
{
MessageBox.Show("Error: The title field was left empty!");
return;
}
if (String.IsNullOrEmpty(description))
{
MessageBox.Show("Error: The description field was left empty!");
return;
}
if (String.IsNullOrEmpty(place))
{
MessageBox.Show("Error: The place field was left empty!");
return;
}
if (date < currentDate)
{
MessageBox.Show("Error: The date must be in the future!");
return;
}
if (date == currentDate && time < currentTime)
{
MessageBox.Show("Error: The time must be in the future!");
return;
}
}
然后我有一个名为 AddReminderForm 的表单,它继承自 AddEditReminderForm 。我正在覆盖 buttonSave_Click 事件处理程序,以便除了在基类中执行的正常操作之外还保存提醒。以下是 AddReminderForm 的代码:
using System;
using System.Windows.Forms;
using Reminder.Classes;
namespace Reminder
{
public partial class AddReminderForm : AddEditReminderForm
{
public AddReminderForm()
{
InitializeComponent();
this.Text = "Add Reminder Form";
Label labelFormHeading = this.Controls["labelFormHeading"] as Label;
labelFormHeading.Text = "Add Reminder";
}
protected override void buttonSave_Click(object sender, EventArgs e)
{
base.buttonSave_Click(sender, e);
AddReminderOperation();
}
protected void AddReminderOperation()
{
ReminderClass reminder = new ReminderClass();
reminder.Id = ReminderHelper.GetCounter();
reminder.Title = title;
reminder.Description = description;
reminder.Place = place;
reminder.Date = date;
reminder.Time = time;
ReminderHelper.AddReminder(reminder);
MessageBox.Show("The reminder has been successfully saved!");
this.Close();
}
}
}
现在,我遇到的问题是,当 AddReminderForm 打开时,如果 PerformValidations 方法中的某个验证失败,则会显示消息框但执行没有停止,提醒仍然保存。如果其中一个验证失败,我该如何中断执行?我正在使用return,但如果我没记错,return只会停止执行当前方法。感谢。
答案 0 :(得分:1)
我会在您的基类ValidateAndSave
中创建一个方法,该方法从事件处理程序调用:
protected void ValidateAndSave()
{
if (this.PerformValidations())
{
this.Save();
}
}
private void buttonSave_Click(object sender, EventArgs e)
{
this.ValidateAndSave();
}
protected bool PerformValidations()
/* could be virtual, if you want to do additional checks in derived classes */
{ ... }
protected virtual void Save()
{ ... }
如果所有验证都可以,则PerformValidations
会返回true
。然后调用save,您可以在派生类中覆盖它。