如何遍历特定表单的所有打开实例? [英] How can I loop through all the open instances of a particular form?

查看:49
本文介绍了如何遍历特定表单的所有打开实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要更新动态创建的Form2的列表框.假设在必须更新此ListBox的情况下(当然是在Form1中),我没有此Form2的引用,因此无法调用UpdateList方法(不,我不能使其变为静态)

I need to update a ListBox of a Form2 created dynamically. Let's say that in the event where I have to update this ListBox (in Form1 of course) I don't have a reference of this Form2 so I can't call the UpdateList method (and no, I can't make it static).

我什至不知道是否打开了Form2,它是否可以打开.

I don't even know if there is a Form2 opened, it could be or not.

您有什么建议?

有没有办法遍历Form2的所有开放方式?

Is there a way to loop through all the open istances of Form2?

代码示例:

//Form1

public void event()
{
    //UPDATE FORM2 LISTBOX
}

//SOMEWHERE IN FORM1

Form2 runTime = new Form2();

//Form2

public void UpdateList()
{
    //UPDATE LISTBOX
}

推荐答案

我不确定您到底要实现什么.但是在我看来,您可以迭代打开的表单的集合:

I'm not sure what exactly do you want to implement. But it seems to me that you can just iterate through the collection of opened forms:

var formsList  = Application.OpenForms.OfType<Form2>();
listBox.Items.AddRange(formsList.Select(f=>f.Text).ToArray());

此行将为您提供应用程序中所有打开的Form2实例的IEnumerable.您可能要使用自己的字符串表示形式(而不是上面代码段中使用的格式标题)

This line will give you the IEnumerable of all open Form2 instances in your application. You might want to use your own string representation (not the form caption used in the snippet above)

这篇关于如何遍历特定表单的所有打开实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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