c# - 只打开一个来自用户控件的表单 [英] c# - open only one form from user control

查看:69
本文介绍了c# - 只打开一个来自用户控件的表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好。

我有一个用户控件和一个按钮。

当我点击按钮时,会打开一个新表格。



我这样做:



Hello.
I have a user control and a button.
When I click on the button, a new form is opened.

I do it in this way:

protected static MyForm myForm1 = new MyForm();
....

public void buttonClicked()   // called by the button clicked event
{
myForm = new myForm();
myForm.Show();
}





问题是,当我再次点击按钮时,将打开另一个表格。

我只想要一个表格才能打开。



我该怎么做?


谢谢

推荐答案

你需要做几件事。

1)创建一个持有一个实例的局部变量父表单类中的子表单。

var MyFormObj;

2)在按钮单击处理程序中,您创建一个实例如果形式尚未存在并显示它。

如果表格已经存在,那么你只需要显示它。

You need to do a couple things.
1) Create a local variable holding an instance of the subform in the parent forms class.
var MyFormObj;
2) In your button click handler you create an instance of the form if it doesn't already exist and show it.
If the form already exists then you just show it.
if( MyFormObj == null )
{
   MyFormObj = new myForm();
}
MyFormObj.Show();


另一种可能性是在 MyFormObj中放置一个静态并且有一个在初始化表单时设置的变量,然后在表单被销毁时重置。然后只有在重置变量时才创建一个新实例。



还有Application.OpenForms Property [ ^ ]。
Another possibilitiy is to put a static in the MyFormObj and have a variable that is set when form is initialized, and then reset when form is destroyed. Then only create a new instance if the variable is reset.

There is also the Application.OpenForms Property[^].






这是我的解决方案



Hi,

This is my solution

public void buttonClicked()   // called by the button clicked event
{
    // looking for opened forms collection
    var _myForm = (MyForm)Application.OpenForms["myForm"];
        if (_myForm == null)
            myForm = new myForm{ name = "myForm"};

    // finally show the form
    _myForm.Show();
}





希望它会有所帮助

问候



Hope it will help
Regards


这篇关于c# - 只打开一个来自用户控件的表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆