C# 从其他类中查找表单实例
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17514251/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
find form instance from other class
提问by panjo
I have Main form with list of data inside listBox. On button click I'm opening new form to create new data object (Main form is inactive in background), when new data is submitted listobox inside main form should be populated with that new object.
我有一个包含列表框内数据列表的主表单。单击按钮时,我打开新表单以创建新数据对象(主表单在后台处于非活动状态),当提交新数据时,主表单内的列表框应填充该新对象。
I was thinking following:
我在想以下:
- When Form2 is submitted I was thinking to find MainForm instance and kill that instance and after that it should be easy, load again list of data from the db and display in the listbox.
- 当 Form2 提交时,我想找到 MainForm 实例并杀死该实例,然后应该很容易,再次从数据库加载数据列表并显示在列表框中。
Question is:
问题是:
If Form1 is created and on some event Form2 is instantiated with showDialog so Form1 is inactive until data is submitted how to find Form1 instance before Form2 is closed?
如果创建了 Form1 并且在某些事件上 Form2 使用 showDialog 实例化,因此 Form1 在提交数据之前处于非活动状态如何在 Form2 关闭之前找到 Form1 实例?
So again, how to find instance of Form1 class from Form2 class?
那么,如何从 Form2 类中找到 Form1 类的实例?
Thanks
谢谢
采纳答案by Jurgen Camilleri
You can get a reference to any of the application's currently open forms by using the Application.OpenFormsproperty. Formsin this FormCollectioncan be accessed by index like so:
您可以使用该Application.OpenForms属性获取对应用程序当前打开的任何表单的引用。Forms这FormCollection可以通过索引访问,如下所示:
var form1 = Application.OpenForms[0];
or by the form's Nameproperty like so:
或通过表单的Name属性,如下所示:
Form form1 = Application.OpenForms["Form1"];
Hope this helps.
希望这可以帮助。
回答by Winks
if you call
如果你打电话
Form1.ShowDialog(this)
then you'll be able to get a reference to the calling form with
然后您将能够获得对调用表单的引用
this.Owner.Name
in the second form (Form2 in your case)
在第二种形式中(在你的情况下为 Form2)
see http://msdn.microsoft.com/en-us/library/system.windows.forms.form.showdialog.aspx
请参阅http://msdn.microsoft.com/en-us/library/system.windows.forms.form.showdialog.aspx

