111,094
社区成员




public partial class Form1 : Form
{
private Dictionary<string, string> messagePool = new Dictionary<string, string>();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// Message可以统一放到Resource里。
messagePool.Add("E0001", "请输入用户名。");
messagePool.Add("E0002", "请输入密码。");
}
private void ValidateNullEmptyInput(Control control)
{
if (string.IsNullOrEmpty(control.Text))
throw new InputCheckException(control.Name, "E0001");
}
private void HandlerInputException(InputCheckException inputEx)
{
MessageBox.Show(messagePool[inputEx.MessageID]);
Control[] controls = this.Controls.Find(inputEx.ControlName, true);
if (controls != null && controls.Length > 0)
controls[0].Focus();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
// 输入验证
ValidateNullEmptyInput(this.textBox1);
// 调用某业务逻辑
// logicXXX.Execute(...);
}
catch (InputCheckException inputEx)
{
// 处理验证错误
HandlerInputException(inputEx);
}
catch (Exception ex)
{
MessageBox.Show("未知的错误:" + ex.Message);
// Log错误堆栈
Trace.WriteLine(ex.StackTrace);
}
}
}
public class InputCheckException : ApplicationException
{
public string ControlName
{ get; private set; }
public string MessageID
{ get; private set; }
public InputCheckException(string controlName, string messageID)
{
ControlName = controlName;
MessageID = messageID;
}