繁体   English   中英

在设计器中打开UserControl时VisualStudio中的错误

[英]Errors in VisualStudio when opening UserControl in designer

背景 :我已经创建了这个UserControl。 在用户控件的构造函数中,我调用一个函数,该函数从数据库中检索一些值。 如果在检索值时发生错误,则会显示一个说明错误的消息框。 到现在为止还挺好。

问题:我创建了一个表单(其中包括其他元素)包括我的UserControl。 现在,当我打开此表单(甚至UserControl本身)时,将调用构造函数(我想这样可以准确地绘制它),并且由于数据库不可用,因此显示了消息框(上面解释了)。

如何防止这种情况发生?

我只想清楚:代码在运行时效果很好。 一切都按设计。 仅在发生问题的Visual Studio的Designer视图(如果需要的话,为2008 SP1)中。 但是,在Designer中这很糟糕,尤其是在连接失败时应用程序尝试重新连接时。 每次进入Designer模式时,Visual Studio都会冻结约20秒(重新连接超时),这将终止我的工作流程。

您可以检查控件是否以设计模式显示:

http://msdn.microsoft.com/zh-CN/library/system.componentmodel.component.designmode.aspx

/编辑:正如人们在对另一个答案的注释中指出的那样,DesignMode属性在构造函数中不可用。 因此,最好的解决方案可能是将数据库内容移至“ Load”之类的事件中,并在其中使用DesignMode属性。

通过在我的Program类上有一个名为IsRunning的全局静态属性,可以解决此问题。

当程序在main方法中启动时,将IsRunning属性设置为true。 然后在用户控件的构造函数中,我可以轮询属性IsRunning以确定我是否执行特定的代码,在您的情况下,这些代码将尝试访问数据库...

编辑:这是一些代码...

private static bool _running = false;

    /// <summary>
    /// Gets or sets a value indicating whether this <see cref="Program"/> is running.
    /// This property is used for design time WSOD issues and is used instead of the 
    /// DesignMode property of a control as the DesignMode property has been said to be
    /// unreliable.
    /// </summary>
    /// <value><c>true</c> if running; otherwise, <c>false</c>.</value>
    public static bool Running
    {
        get
        {
            return _running;
        }
    }


    static void Main(string[] args)
    {
        Initialize();


        _running = true;

....

在我的用户控件中...

    public AssignmentList()
    {
        InitializeComponent();

        if (!Program.Running)
        {
            return;
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM