在表单加载时,我需要进行X
次检查以确定是否打开或关闭表单。以下是一个简单的例子。
public partial class BaseForm : Form
{
private void BaseForm_Load(object sender, EventArgs e)
{
if(!IsUserValid())
MessageBox.Show("User is not valid");
}
private bool IsUserValid()
{
List<string> allowedUsernames = new List<string>();
using (SqlConnection con = new SqlConnection(_connectionString))
{
//Get a list of usernames, none of which are "Developer" usernames
}
return allowedUsernames.Any(username => username == Environment.UserName);
}
}
public partial class DerivedForm : BaseForm
{
}
上面的示例,无论用户名如何,我都可以在设计器中完美地加载表单。如果我执行其他表单DerivedForm
并继承基础,则会调用Load
,因此会在设计模式中显示MessageBox
然后Close
表单,但不会给我访问设计器,为什么派生的WindowsForm
需要使用Load
事件,但基数不是?如果你正在使用WindowsForms
进行继承,那么不使用Load事件是明智的吗?
我只是觉得这很奇怪,有人知道吗?
答案 0 :(得分:1)
还有另一个question解决了类似的问题。此外,接受的答案提供了克服此行为的解决方案:https://stackoverflow.com/a/2427420/674700。
基本上,在您的情况下,添加DesignTimeHelper
类,并使用以下修改来查看差异:
private void BaseForm_Load(object sender, EventArgs e)
{
if (!DesignTimeHelper.IsInDesignMode)
{
if (!IsUserValid())
{
MessageBox.Show("User is not valid");
}
}
else
{
MessageBox.Show("Called from VS");
}
}