简体   繁体   English

拖放用户控件将无法在.net windows项目中工作

[英]Drag and drop the user control won't work in .net windows project

I created a user control and it shows up on the tool box as form components. 我创建了一个用户控件,它在工具箱中显示为表单组件。 Then when I try to drag and drop the user control on to a form , I get this visual studio error. 然后当我尝试将用户控件拖放到表单上时,我得到了这个visual studio错误。

" The specified named connection is either not found in the configuration ,not intended to be used with the entity client provider or not valid." “在配置中找不到指定的命名连接,不打算与实体客户端提供程序一起使用或无效。”

Why am I getting this error? 为什么我收到此错误?

But some other user controls I can drag and drop which are under the same project. 但是我可以拖放一些其他用户控件在同一个项目下。 I don't know what I missed in creating this user control. 我不知道在创建这个用户控件时我错过了什么。

Beware that code in the UserControl class runs at design time. 请注意UserControl类中的代码在设计时运行。 The constructor, the OnLoad method and Load event. 构造函数,OnLoad方法和Load事件。 But also methods like OnPaint(). 但也有像OnPaint()这样的方法。 If this code does anything that depends on the environment being setup properly, that code is liable to throw an exception and cause the designer to change its mind about adding the control to the form. 如果此代码执行任何取决于正确设置的环境的代码,则该代码可能会抛出异常并导致设计者改变其关于将控件添加到表单的想法。 That certainly seems to be the case when you get a "not found in the configuration" error, there is no configuration file yet. 当你在“配置中找不到”错误时,似乎就是这种情况,但还没有配置文件。

Use the DesignMode properly to skip such code. 正确使用DesignMode可以跳过此类代码。 Like this: 像这样:

    protected override void OnLoad(EventArgs e) {
        if (!this.DesignMode) {
            // Do stuff...
        }
        base.OnLoad(e);
    }

this error show if you put the code of loading data from database into the constructor of userControl. 如果您将数据库中的数据加载到userControl的构造函数中,则会显示此错误。

"loading data or initialize entity framework" “加载数据或初始化实体框架”

so the solution is to move the code of loading data from constructor to a method. 所以解决方案是将加载数据的代码从构造函数移动到方法。 you can call it "loadData". 你可以称之为“loadData”。

and call this method "loadData" in the constructor of the parent form 并在父窗体的构造函数中调用此方法“loadData”

As Hans says, you might need to use the DesignMode property in the Constructor or OnLoad. 正如Hans所说,您可能需要在Constructor或OnLoad中使用DesignMode属性。 Also, make sure any public properties that use the connection have this attribute: 此外,请确保使用该连接的任何公共属性都具有此属性:

[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public string Foo
{
    get;
    set;
}

That way, the designer won't attempt to set them when you add the control to a form. 这样,当您将控件添加到表单时,设计器不会尝试设置它们。 This is always a good habit to get into anyway for properties that you won't be setting at design time. 对于您在设计时不会设置的属性,这始终是一个好习惯。

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

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